Exemple #1
1
        // Initialize all of the default certificates and protocols
        public SslServer()
        {
            // Initialize the Socket
            serverSocketType = SocketType.Stream;
            serverProtocolType = ProtocolType.Tcp;

            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                cert = new X509Certificate(CertificatesAndCAs.emuCert, "NetMF");
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caEmuCert) };
            }
            else
            {
                // Initialize the SslStream
                cert = new X509Certificate(CertificatesAndCAs.newCert);
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caCert) };
            }
            verify = SslVerification.NoVerification;
            sslProtocols = new SslProtocols[] { SslProtocols.Default };

            // Create a TCP/IP (IPv4) socket and listen for incoming connections.
            serverSocket = new Socket(AddressFamily.InterNetwork, serverSocketType, serverProtocolType);
            serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);

            serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            serverEp = (IPEndPoint)serverSocket.LocalEndPoint;

            Debug.Print("Listening for a client to connect...");
            serverSocket.Listen(1);
        }
 public NetworkDevice(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, EndPoint endPoint)
 {
     _AddressFamily = addressFamily;
     _SocketType = socketType;
     _ProtocolType = protocolType;
     _EndPoint = endPoint;
 }
Exemple #3
0
        public BINLSocket(IPEndPoint endpoint, bool broadcast = false, bool enableMulticast = false, int buffersize = 1024, SocketType type = SocketType.BINL)
        {
            try
            {
                this.localEndPoint = endpoint;
                this.broadcast = broadcast;
                this.buffersize = buffersize;
                this.type = type;
                this.reuseAddress = Settings.ReUseAddress;

                this.socket = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, ProtocolType.Udp);
                this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, this.broadcast);
                this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, this.reuseAddress);

                this.state = new SocketState();
                this.state.Type = this.type;
                this.state.Buffer = new byte[this.buffersize];
                this.state.Buffersize = this.buffersize;
                this.state.Socket = this.socket;

                this.socket.Bind(this.localEndPoint);
                this.socket.BeginReceiveFrom(this.state.Buffer, 0, this.state.Buffersize, 0,
                    ref this.localEndPoint, new AsyncCallback(this.Received), this.state);
            }
            catch (SocketException ex)
            {
                Errorhandler.Report(LogTypes.Error, "[BINL] Socket Error {0}: {1}".F(ex.ErrorCode, ex.Message));
            }
        }
Exemple #4
0
 /// <summary>
 /// Initializes a new instance of the ProxySocket class.
 /// </summary>
 /// <param name="addressFamily">One of the AddressFamily values.</param>
 /// <param name="socketType">One of the SocketType values.</param>
 /// <param name="protocolType">One of the ProtocolType values.</param>
 /// <param name="proxyUsername">The username to use when authenticating with the proxy server.</param>
 /// <param name="proxyPassword">The password to use when authenticating with the proxy server.</param>
 /// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
 /// <exception cref="ArgumentNullException"><c>proxyUsername</c> -or- <c>proxyPassword</c> is null.</exception>
 public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, string proxyUsername, string proxyPassword)
     : base(addressFamily, socketType, protocolType)
 {
     ProxyUser = proxyUsername;
     ProxyPass = proxyPassword;
     ToThrow = new InvalidOperationException();
 }
Exemple #5
0
	public P2PClient(string ip,int point,SocketType socketType=SocketType.Dgram,ProtocolType protocolType=ProtocolType.Udp)
	{
		this.ip=ip;
		this.point=point;
		this.protocolType =protocolType;
		this.socketType=socketType;
	}
		private IntPtr Socket_internal(AddressFamily family,
		SocketType type,
		ProtocolType proto,
		out int error)
		{
			throw new System.NotImplementedException();
		}
Exemple #7
0
        public static unsafe SafeCloseSocket CreateSocket(SocketInformation socketInformation, out AddressFamily addressFamily, out SocketType socketType, out ProtocolType protocolType)
        {
            SafeCloseSocket handle;
            Interop.Winsock.WSAPROTOCOL_INFO protocolInfo;

            fixed (byte* pinnedBuffer = socketInformation.ProtocolInformation)
            {
                handle = SafeCloseSocket.CreateWSASocket(pinnedBuffer);
                protocolInfo = (Interop.Winsock.WSAPROTOCOL_INFO)Marshal.PtrToStructure<Interop.Winsock.WSAPROTOCOL_INFO>((IntPtr)pinnedBuffer);
            }

            if (handle.IsInvalid)
            {
                SocketException e = new SocketException();
                if (e.SocketErrorCode == SocketError.InvalidArgument)
                {
                    throw new ArgumentException(SR.net_sockets_invalid_socketinformation, "socketInformation");
                }
                else
                {
                    throw e;
                }
            }

            addressFamily = protocolInfo.iAddressFamily;
            socketType = (SocketType)protocolInfo.iSocketType;
            protocolType = (ProtocolType)protocolInfo.iProtocol;
            return handle;
        }
Exemple #8
0
 private Socket(AddressFamily family, SocketType type, ProtocolType proto, IntPtr native)
 {
     this.family = family;
     this.type = type;
     this.proto = proto;
     this.native = native;
 }
 public SocketManager(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _addressFamily = addressFamily;
     _socketType = socketType;
     _protocolType = protocolType;
     _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
		public TZmqServer (TProcessor processor, Context ctx, String endpoint, SocketType sockType)
		{
			new TSimpleServer (processor,null);
			_socket = ctx.Socket (sockType);
			_socket.Bind (endpoint);
			_processor = processor;
		}
Exemple #11
0
        public static async Task<IDisposableConnection<ArraySegment<byte>>> CreateConnection(
            EndPoint endpoint,
            SocketType socketType = SocketType.Stream,
            ProtocolType protocolType = ProtocolType.Tcp)
        {
            var socket = new Socket(socketType, protocolType);
            bool disposeSocket = false;
            try
            {                
                using (SocketAwaitableEventArgs args = new SocketAwaitableEventArgs())
                {
                    args.RemoteEndPoint = endpoint;
                    await socket.ConnectSocketAsync(args);
                }
            }
            catch (Exception)
            {
                disposeSocket = true;
                throw;
            }
            finally
            {
                if (disposeSocket)
                {
                    socket.Dispose();
                    socket = null;
                }
            }

            return socket.ToConnection();
        }
Exemple #12
0
 public Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     SetAddressFamily(addressFamily);
     SetProtocolType(protocolType);
     SetSocketType(socketType);
     return new Socket(this.addressFamily, this.socketType, this.protocolType);
 }
 protected SingleReceiveLoopProxyReactor(IPAddress localAddress, int localPort, NetworkEventLoop eventLoop,
     IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator,
     SocketType socketType = SocketType.Stream, ProtocolType protocol = ProtocolType.Tcp,
     int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
     : base(localAddress, localPort, eventLoop, encoder, decoder, allocator, socketType, protocol, bufferSize)
 {
 }
Exemple #14
0
	public P2PServer(int point,SocketType socketType=SocketType.Dgram,ProtocolType protocolType=ProtocolType.Udp)
	{
		this.point=point;
		this.protocolType =protocolType;
		this.socketType=socketType;
	
	}
Exemple #15
0
			public void Reset (Socket socket, IPEndPoint ip)
			{
				this.addressFamily = socket.AddressFamily;
				this.socketType = socket.SocketType;
				this.protocolTtype = socket.ProtocolType;
				this.RemoteEndPoint = ip;
			}
Exemple #16
0
	public TCPClient(string ip,int point,SocketType socketType=SocketType.Stream,ProtocolType protocolType=ProtocolType.Tcp)
	{
		this.ip=ip;
		this.point=point;
		this.protocolType =protocolType;
		this.socketType=socketType;
	}
Exemple #17
0
 public ServerAcceptor(SocketType socketType, ProtocolType protocolType, ISocketAsyncEventArgsPool acceptorPool, Func<SocketAsyncEventArgs> acceptorFactory)
 {
     this.socketType = socketType;
     this.protocolType = protocolType;
     this.acceptorPool = acceptorPool;
     this.acceptorFactory = acceptorFactory;
 }
Exemple #18
0
        public SocketServer(int portNumber, AddressFamily addressFamily, SocketType socketType,
            ProtocolType protocolType)
        {
            this.portNumber = portNumber;
            this.addressFamily = addressFamily;
            this.socketType = socketType;
            this.protocolType = protocolType;

            clientAddresses = new List<string>();
            clientTable = new Dictionary<string, StateObject>();
            recentlyReceivedStates = new List<StateObject>();
            removeList = new List<string>();

            listenEvent = new ManualResetEvent(false);
            shutDownEvent = new ManualResetEvent(false);
            sendEvent = new ManualResetEvent(false);

            listener = null;
            sendBufferSize = INITIAL_BUFFER_SIZE;
            recvBufferSize = INITIAL_BUFFER_SIZE;
            ShutdownWaitTimeout = 5000;

            enableEncryption = false;
            initialized = false;
            copyingRecvBuffer = false;
            isShuttingDown = false;
            transmittingData = false;
            receivingData = false;
        }
        /// <summary>
        /// Initializes the socket
        /// </summary>`
        public void init(int offset, string ipAddress)
        {
            socketType = SocketType.Stream;
            protocolType = ProtocolType.Tcp;
            //addressFamily = AddressFamily.InterNetwork;
            addressFamily = AddressFamily.InterNetwork;
            try
            {
                ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress[] addr = ipEntry.AddressList;
                //endpoint = new IPEndPoint(addr[0], port);
                for (int i = 0; i < addr.Length; i++)
                {
                    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                }
                if (ipAddress == "")
                {
                    address = addr[addr.Length - offset];
                }
                else
                {
                    address = IPAddress.Parse(ipAddress);
                }
                Console.WriteLine("Using the Address {0}: {1}", address.ToString(), port);
                endpoint = new IPEndPoint(address, port);
            }
            catch (SocketException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            createSocket();

        }
Exemple #20
0
        /// <summary>
        /// 
        /// </summary>
        public SocketAsyncClient(IPEndPoint remoteEndPoint, int bufferSize, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            _remoteEndPoint = remoteEndPoint;
            _client = new Socket(addressFamily, socketType, protocolType);
            socketObject = new SocketObject(Guid.NewGuid(), _client);
            int maxConnection = 1;
            int numOfSaeaForRecSend = maxConnection * OpsToPreAlloc;
            _readWritePool = new SocketAsyncPool(numOfSaeaForRecSend);
            int numSize = numOfSaeaForRecSend * bufferSize;
            _bufferManager = new BufferManager(numSize, bufferSize);
            _bufferManager.InitBuffer();

            _saeaProxy = new SocketAsyncEventArgsProxy(bufferSize);
            _saeaProxy.ReceiveCompleted += OnReceiveCompleted;
            _saeaProxy.SendCompleted += OnSendCompleted;
            _saeaProxy.ClosedHandle += OnSocketClosing;

            SocketAsyncEventArgs saea;
            for (int i = 0; i < numOfSaeaForRecSend; i++)
            {
                saea = _saeaProxy.CreateNewSaea();
                _bufferManager.SetBuffer(saea);
                saea.UserToken = new DataToken(saea.Offset);
                _readWritePool.Push(saea);
            }
        }
    /// <summary>
    /// Accepts the specified number of incoming connection attempts and creates new <see cref="Socket"/> objects.
    /// </summary>
    /// <param name="addressFamily">One of the <see cref="AddressFamily"/> values.</param>
    /// <param name="socketType">One of the <see cref="SocketType"/> values.</param>
    /// <param name="protocolType">One of the <see cref="ProtocolType"/> values.</param>
    /// <param name="localEndPoint">The local <see cref="EndPoint"/> to associate with the <see cref="Socket"/> that 
    /// will be accepting connections.</param>
    /// <param name="count">The maximum number of connections to accept.</param>
    /// <param name="acceptSocketFactory">Called when ready to accept a new <see cref="Socket"/>, up to the specified <paramref name="count"/>.
    /// This function may return <see langword="null"/> to create new sockets automatically.</param>
    /// <returns>An observable sequence containing the connected <see cref="Socket"/> objects.</returns>
    public static IObservable<Socket> Accept(
      AddressFamily addressFamily,
      SocketType socketType,
      ProtocolType protocolType,
      IPEndPoint localEndPoint,
      int count,
      Func<Socket> acceptSocketFactory)
    {
      Contract.Requires(localEndPoint != null);
      Contract.Requires(count > 0);
      Contract.Requires(acceptSocketFactory != null);
      Contract.Ensures(Contract.Result<IObservable<Socket>>() != null);

      return Observable.Using(
        () => new Socket(addressFamily, socketType, protocolType),
        socket =>
        {
          socket.Bind(localEndPoint);
          socket.Listen(count);

          var e = new SocketAsyncEventArgs();

          return Observable
            .Defer(() =>
            {
              e.AcceptSocket = acceptSocketFactory();		// Work item 23871

              return socket.AcceptObservable(e);
            })
            .Select(r => r.AcceptSocket)
            .Repeat(count);
        });
    }
Exemple #22
0
        /// <summary>
        /// Creates client connector.
        /// </summary>
        public ClientConnector(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs connector)
        {
            this.socketType = socketType;
            this.protocolType = protocolType;
            this.connector = connector;

            connector.Completed += OnConnectCompleted;
        }
 public void Connect(IPEndPoint p,
     AddressFamily family = AddressFamily.InterNetwork,
     SocketType type = SocketType.Stream,
     ProtocolType protoType = ProtocolType.Tcp)
 {
     _ClientProfSocket = new Socket(family, type, protoType);
     _ClientProfSocket.Connect(p);
 }
Exemple #24
0
 public CreateEvent(EventInformation eventInformation, AddressFamily addressFamily, SocketType socketType,
                    ProtocolType protocolType, uint result)
     : base(eventInformation)
 {
     m_addressFamily = addressFamily;
     m_socketType = socketType;
     m_protocolType = protocolType;
     m_result = result;
 }
Exemple #25
0
    public AsyncSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
    {
      m_addressFamily = addressFamily;
      m_socketType = socketType;
      m_protocolType = protocolType;

      InitSocket();
      InitDynamicMethods();
    }
Exemple #26
0
		public Socket(AddressFamily family, SocketType type, ProtocolType proto) {
			this.family = family;
			this.type = type;
			this.proto = proto;

			int error;
			this.native = Internal_CreateSocket((int)family, (int)type, (int)proto, out error);
			this.CheckError(error);
		}
Exemple #27
0
            //--//

            public StressSocketPair(ProtocolType prot, SocketType st)
                : base(prot, st)
            {
                if (prot == ProtocolType.Tcp)
                {
                    socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);
                    socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);
                }
                evt = new AutoResetEvent( false );
            }
Exemple #28
0
 public static SafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     SafeCloseSocket handle = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType);
     if (handle.IsInvalid)
     {
         // Failed to create the win32 socket, throw.
         throw new SocketException();
     }
     return handle;
 }
Exemple #29
0
 public ConnectionManager(Dictionary<Byte[], Action> opList, IPAddress listenIP, UInt16 listenPort, SocketType sockType = SocketType.Stream, ProtocolType protoType = ProtocolType.Tcp, AddressFamily addrFamily = AddressFamily.InterNetwork)
 {
     actions = opList;
     ip = listenIP;
     port = listenPort;
     this.sockType = sockType;
     this.protoType = protoType;
     this.addrFamily = addrFamily;
     StartListener();
 }
Exemple #30
0
		public IZmqSocket CreateSocket(SocketType type)
		{
			if (_disposed) throw new ObjectDisposedException("StubContext disposed");

			var socket = _creator(type);

			this.LastSocketCreatedByType[type] = socket;

			return socket;
		}
Exemple #31
0
 public ISocket New_Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     return(client.aClient.GetSharedClass <ISocket>(typeof(Lite_Socket), addressFamily, socketType, protocolType));
 }
Exemple #32
0
 public void Ctor_Failure(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     Assert.Throws <SocketException>(() => new Socket(addressFamily, socketType, protocolType));
 }
 internal static partial Error GetSocketType(SafeSocketHandle socket, out AddressFamily addressFamily, out SocketType socketType, out ProtocolType protocolType, out bool isListening);
Exemple #34
0
 public static extern IntPtr WSASocket([In] AddressFamilies af, [In] SocketType type, [In] Protocol protocol, [In] IntPtr lpProtocolInfo, [In] Int32 group, [In] SocketFlags dwFlags);
 public MdoSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
     : base(addressFamily, socketType, protocolType)
 {
     allDone = new ManualResetEvent(false);
 }
        static NeuronSource CreateConnection(string address, int port, int commandServerPort, SocketType socketType)
        {
            NeuronSource source                 = null;
            IntPtr       socketReference        = IntPtr.Zero;
            IntPtr       commandSocketReference = IntPtr.Zero;

            if (socketType == SocketType.TCP)
            {
                socketReference = NeuronDataReader.BRConnectTo(address, port);
                if (socketReference != IntPtr.Zero)
                {
                    Debug.Log(string.Format("[NeuronConnection] Connected to {0}:{1}.", address, port));
                }
                else
                {
                    Debug.LogError(string.Format("[NeuronConnection] Connecting to {0}:{1} failed.", address, port));
                }
            }
            else
            {
                socketReference = NeuronDataReader.BRStartUDPServiceAt(port);
                if (socketReference != IntPtr.Zero)
                {
                    Debug.Log(string.Format("[NeuronConnection] Start listening at {0}.", port));
                }
                else
                {
                    Debug.LogError(string.Format("[NeuronConnection] Start listening at {0} failed.", port));
                }
            }

            if (socketReference != IntPtr.Zero)
            {
                if (connections.Count == 0)
                {
                    RegisterReaderCallbacks();
                }

                if (commandServerPort > 0)
                {
                    // connect to command server
                    commandSocketReference = NeuronDataReader.BRConnectTo(address, commandServerPort);
                    if (commandSocketReference != IntPtr.Zero)
                    {
                        Debug.Log(string.Format("[NeuronConnection] Connected to command server {0}:{1}.", address, commandServerPort));
                    }
                    else
                    {
                        Debug.LogError(string.Format("[NeuronConnection] Connected to command server {0}:{1} failed.", address, commandServerPort));
                    }
                }

                source = new NeuronSource(address, port, commandServerPort, socketType, socketReference, commandSocketReference);
                connections.Add(source.guid, source);
                socketReferencesIndex.Add(socketReference, source);
                if (commandSocketReference != IntPtr.Zero)
                {
                    commandSocketReferenceIndex.Add(commandSocketReference, source);
                }
            }

            return(source);
        }
Exemple #37
0
 protected ReactorBase(IPAddress localAddress, int localPort, NetworkEventLoop eventLoop, IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator, SocketType socketType = SocketType.Stream, ProtocolType protocol = ProtocolType.Tcp, int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
 {
     Decoder       = decoder;
     Encoder       = encoder;
     Allocator     = allocator;
     LocalEndpoint = new IPEndPoint(localAddress, localPort);
     Listener      = new Socket(AddressFamily.InterNetwork, socketType, protocol);
     if (protocol == ProtocolType.Tcp)
     {
         Transport = TransportType.Tcp;
     }
     else if (protocol == ProtocolType.Udp)
     {
         Transport = TransportType.Udp;
     }
     Backlog           = NetworkConstants.DefaultBacklog;
     EventLoop         = eventLoop;
     ConnectionAdapter = new ReactorConnectionAdapter(this);
     BufferSize        = bufferSize;
 }
 public ProxyEncryptSocket(AddressFamily af, SocketType type, ProtocolType protocol)
 {
     _socket = new Socket(af, type, protocol);
 }
Exemple #39
0
 public XSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType)
 {
 }
Exemple #40
0
 public void DualMode_Success(SocketType socketType, ProtocolType protocolType)
 {
     using (new Socket(socketType, protocolType))
     {
     }
 }
Exemple #41
0
#pragma warning disable IDE1006 // Naming Styles - these are Win32 function names
            internal static extern int socket(AddressFamily af, SocketType type, ProtocolType protocol);
Exemple #42
0
 public SocketListener(SocketType type, IPEndPoint host, Func <IProtocol> factory)
 {
     _type    = type;
     _host    = host;
     _factory = factory;
 }
Exemple #43
0
 public void DualMode_Failure(SocketType socketType, ProtocolType protocolType)
 {
     Assert.Throws <SocketException>(() => new Socket(socketType, protocolType));
 }
Exemple #44
0
 public SocketListener(SocketType type, IPEndPoint host, IProtocolFactory factory)
     : this(type, host, factory.Create)
 {
     // _context = this.CreateContext(type, host);
 }
Exemple #45
0
 public TZmqClient(Context ctx, String endpoint, SocketType sockType)
 {
     _sock     = ctx.Socket(sockType);
     _endpoint = endpoint;
 }
Exemple #46
0
        public async Task Ctor_SafeHandle_Tcp_SendReceive_Success(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            using var orig     = new Socket(addressFamily, socketType, protocolType);
            using var listener = new Socket(addressFamily, socketType, protocolType);
            listener.Bind(new IPEndPoint(addressFamily == AddressFamily.InterNetwork ? IPAddress.Loopback : IPAddress.IPv6Loopback, 0));
            listener.Listen(1);
            await orig.ConnectAsync(listener.LocalEndPoint);

            using var server = await listener.AcceptAsync();

            using var client = new Socket(orig.SafeHandle);

            Assert.True(client.Connected);
            Assert.Equal(orig.AddressFamily, client.AddressFamily);
            Assert.Equal(orig.SocketType, client.SocketType);
            Assert.Equal(orig.ProtocolType, client.ProtocolType);

            // Validate accessing end points
            Assert.Equal(orig.LocalEndPoint, client.LocalEndPoint);
            Assert.Equal(orig.RemoteEndPoint, client.RemoteEndPoint);

            // Validating accessing other properties
            Assert.Equal(orig.Available, client.Available);
            Assert.True(orig.Blocking);
            Assert.True(client.Blocking);
            AssertEqualOrSameException(() => orig.DontFragment, () => client.DontFragment);
            AssertEqualOrSameException(() => orig.EnableBroadcast, () => client.EnableBroadcast);
            Assert.Equal(orig.ExclusiveAddressUse, client.ExclusiveAddressUse);
            Assert.Equal(orig.Handle, client.Handle);
            Assert.Equal(orig.IsBound, client.IsBound);
            Assert.Equal(orig.LingerState.Enabled, client.LingerState.Enabled);
            Assert.Equal(orig.LingerState.LingerTime, client.LingerState.LingerTime);
            AssertEqualOrSameException(() => orig.MulticastLoopback, () => client.MulticastLoopback);
            Assert.Equal(orig.NoDelay, client.NoDelay);
            Assert.Equal(orig.ReceiveBufferSize, client.ReceiveBufferSize);
            Assert.Equal(orig.ReceiveTimeout, client.ReceiveTimeout);
            Assert.Equal(orig.SendBufferSize, client.SendBufferSize);
            Assert.Equal(orig.SendTimeout, client.SendTimeout);
            Assert.Equal(orig.Ttl, client.Ttl);
            Assert.Equal(orig.UseOnlyOverlappedIO, client.UseOnlyOverlappedIO);

            // Validate setting various properties on the new instance and seeing them roundtrip back to the original.
            client.ReceiveTimeout = 42;
            Assert.Equal(client.ReceiveTimeout, orig.ReceiveTimeout);

            // Validate sending and receiving
            Assert.Equal(1, await client.SendAsync(new byte[1] {
                42
            }, SocketFlags.None));
            var buffer = new byte[1];

            Assert.Equal(1, await server.ReceiveAsync(buffer, SocketFlags.None));
            Assert.Equal(42, buffer[0]);

            Assert.Equal(1, await server.SendAsync(new byte[1] {
                42
            }, SocketFlags.None));
            buffer[0] = 0;
            Assert.Equal(1, await client.ReceiveAsync(buffer, SocketFlags.None));
            Assert.Equal(42, buffer[0]);
        }
 public ProxySocketTunLocal(AddressFamily af, SocketType type, ProtocolType protocol)
     : base(af, type, protocol)
 {
 }
Exemple #48
0
        public void Ctor_SafeHandle_BasicPropertiesPropagate_Success(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            bool isRawPacket = (addressFamily == AddressFamily.Packet) &&
                               (socketType == SocketType.Raw);

            if (isRawPacket)
            {
                // protocol is the IEEE 802.3 protocol number in network byte order.
                const short ETH_P_ARP = 0x0806;
                protocolType = (ProtocolType)IPAddress.HostToNetworkOrder(ETH_P_ARP);
            }

            Socket tmpOrig;

            try
            {
                tmpOrig = new Socket(addressFamily, socketType, protocolType);
            }
            catch (SocketException e) when(
                e.SocketErrorCode == SocketError.AccessDenied ||
                e.SocketErrorCode == SocketError.ProtocolNotSupported ||
                e.SocketErrorCode == SocketError.AddressFamilyNotSupported)
            {
                // We can't test this combination on this platform.
                return;
            }

            using Socket orig = tmpOrig;
            using var copy    = new Socket(orig.SafeHandle);

            Assert.False(orig.Connected);
            Assert.False(copy.Connected);

            Assert.Null(orig.LocalEndPoint);
            Assert.Null(orig.RemoteEndPoint);
            Assert.False(orig.IsBound);
            if (copy.IsBound)
            {
                // On Unix, we may successfully obtain an (empty) local end point, even though Bind wasn't called.
                Debug.Assert(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) // OSX gets some strange results in some cases, e.g. "@\0\0\0\0\0\0\0\0\0\0\0\0\0" for a UDS
                {
                    switch (addressFamily)
                    {
                    case AddressFamily.InterNetwork:
                        Assert.Equal(new IPEndPoint(IPAddress.Any, 0), copy.LocalEndPoint);
                        break;

                    case AddressFamily.InterNetworkV6:
                        Assert.Equal(new IPEndPoint(IPAddress.IPv6Any, 0), copy.LocalEndPoint);
                        break;

                    case AddressFamily.Unix:
                        Assert.IsType <UnixDomainSocketEndPoint>(copy.LocalEndPoint);
                        Assert.Equal("", copy.LocalEndPoint.ToString());
                        break;

                    default:
                        Assert.Null(copy.LocalEndPoint);
                        break;
                    }
                }
                Assert.Null(copy.RemoteEndPoint);
            }
            else
            {
                Assert.Equal(orig.LocalEndPoint, copy.LocalEndPoint);
                Assert.Equal(orig.LocalEndPoint, copy.RemoteEndPoint);
            }

            Assert.Equal(addressFamily, orig.AddressFamily);
            Assert.Equal(socketType, orig.SocketType);
            Assert.Equal(protocolType, orig.ProtocolType);

            Assert.Equal(addressFamily, copy.AddressFamily);
            Assert.Equal(socketType, copy.SocketType);
            ProtocolType expectedProtocolType = protocolType;

            if (isRawPacket)
            {
                // raw packet doesn't support getting the protocol using getsockopt SO_PROTOCOL.
                expectedProtocolType = ProtocolType.Unspecified;
            }
            Assert.Equal(expectedProtocolType, copy.ProtocolType);

            Assert.True(orig.Blocking);
            Assert.True(copy.Blocking);

            if (orig.AddressFamily == copy.AddressFamily)
            {
                AssertEqualOrSameException(() => orig.DontFragment, () => copy.DontFragment);
                AssertEqualOrSameException(() => orig.MulticastLoopback, () => copy.MulticastLoopback);
                AssertEqualOrSameException(() => orig.Ttl, () => copy.Ttl);
            }

            AssertEqualOrSameException(() => orig.EnableBroadcast, () => copy.EnableBroadcast);
            AssertEqualOrSameException(() => orig.LingerState.Enabled, () => copy.LingerState.Enabled);
            AssertEqualOrSameException(() => orig.LingerState.LingerTime, () => copy.LingerState.LingerTime);
            AssertEqualOrSameException(() => orig.NoDelay, () => copy.NoDelay);

            Assert.Equal(orig.Available, copy.Available);
            Assert.Equal(orig.ExclusiveAddressUse, copy.ExclusiveAddressUse);
            Assert.Equal(orig.Handle, copy.Handle);
            Assert.Equal(orig.ReceiveBufferSize, copy.ReceiveBufferSize);
            Assert.Equal(orig.ReceiveTimeout, copy.ReceiveTimeout);
            Assert.Equal(orig.SendBufferSize, copy.SendBufferSize);
            Assert.Equal(orig.SendTimeout, copy.SendTimeout);
            Assert.Equal(orig.UseOnlyOverlappedIO, copy.UseOnlyOverlappedIO);
        }
Exemple #49
0
 public AsyncSocket(AddressFamily family, SocketType type, ProtocolType protocol)
 {
     _socket = new Socket(family, type, protocol);
 }
Exemple #50
0
 /// <summary>
 ///     Create a new instance of the <see cref="ProtoServer{T}" />.
 ///     Use <see cref="Start" /> to bind and start the socket.
 /// </summary>
 /// <param name="family">
 ///     The <see cref="AddressFamily" />
 ///     this <see cref="System.Net.Sockets.Socket" /> should use
 /// </param>
 /// <param name="type">
 ///     The <see cref="SocketType" /> this
 ///     <see cref="System.Net.Sockets.Socket" /> should use
 /// </param>
 /// <param name="address">The <see cref="IPAddress" /> to start this Protocol on</param>
 /// <param name="port">The Port to start this Protocol on</param>
 public ProtoServer(IPAddress address, int port, AddressFamily family, SocketType type)
 {
     Sockets  = new Dictionary <IPEndPoint, Socket>();
     EndPoint = new IPEndPoint(address, port);
     Socket   = new Socket(family, type, ProtocolType.Tcp);
 }
        public static NeuronSource Connect(string address, int port, int commandServerPort, SocketType socketType)
        {
            NeuronSource source = FindConnection(address, port, socketType);

            if (source != null)
            {
                source.Grab();
                return(source);
            }

            source = CreateConnection(address, port, commandServerPort, socketType);
            if (source != null)
            {
                source.Grab();
                return(source);
            }

            return(null);
        }
Exemple #52
0
        private static Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);

            return(socket);
        }
Exemple #53
0
        /// <summary>
        /// This is the main routine that parses the command line and invokes the server with the
        /// given parameters. For TCP, it creates a listening socket and waits to accept a client
        /// connection. Once a client connects, it waits to receive a "request" message. The
        /// request is terminated by the client shutting down the connection. After the request is
        /// received, the server sends a response followed by shutting down its connection and
        /// closing the socket. For UDP, the socket simply listens for incoming packets. The "request"
        /// message is a single datagram received. Once the request is received, a number of datagrams
        /// are sent in return followed by sending a few zero byte datagrams. This way the client
        /// can determine that the response has completed when it receives a zero byte datagram.
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            string       textMessage = "Server: ServerResponse";
            int          localPort = 5150, sendCount = 10, bufferSize = 4096;
            IPAddress    localAddress = IPAddress.Any;
            SocketType   sockType     = SocketType.Stream;
            ProtocolType sockProtocol = ProtocolType.Tcp;

            // Parse the command line
            for (int i = 0; i < args.Length; i++)
            {
                try {
                    if ((args[i][0] == '-') || (args[i][0] == '/'))
                    {
                        switch (Char.ToLower(args[i][1]))
                        {
                        case 'l':           // Local interface to bind to
                            localAddress = IPAddress.Parse(args[++i]);
                            break;

                        case 'm':           // Text message to put into the send buffer
                            textMessage = args[++i];
                            break;

                        case 'n':           // Number of times to send the response
                            sendCount = System.Convert.ToInt32(args[++i]);
                            break;

                        case 'p':           // Port number for the destination
                            localPort = System.Convert.ToInt32(args[++i]);
                            break;

                        case 't':           // Specified TCP or UDP
                            i++;
                            if (String.Compare(args[i], "tcp", true) == 0)
                            {
                                sockType     = SocketType.Stream;
                                sockProtocol = ProtocolType.Tcp;
                            }
                            else if (String.Compare(args[i], "udp", true) == 0)
                            {
                                sockType     = SocketType.Dgram;
                                sockProtocol = ProtocolType.Udp;
                            }
                            else
                            {
                                FillServerUsage();
                                return;
                            }
                            break;

                        case 'x':           // Size of the send and receive buffers
                            bufferSize = System.Convert.ToInt32(args[++i]);
                            break;

                        default:
                            //queueSocketServer = FillServerUsage();
                            return;
                        }
                    }
                } catch {
                    //MainForm.queueSocketServer = FillServerUsage();
                    return;
                }
            }

            Socket serverSocket = null;

            try {
                IPEndPoint localEndPoint = new IPEndPoint(localAddress, localPort), senderAddress = new IPEndPoint(localAddress, 0);
                Console.WriteLine("Server: IPEndPoint is OK...");
                EndPoint castSenderAddress;
                Socket   clientSocket;
                byte[]   receiveBuffer = new byte[bufferSize], sendBuffer = new byte[bufferSize];
                int      rc;

                FormatBuffer(sendBuffer, textMessage);

                // Create the server socket
                serverSocket = new Socket(localAddress.AddressFamily, sockType, sockProtocol);

                Console.WriteLine("Server: Socket() is OK...");
                // Bind the socket to the local interface specified
                serverSocket.Bind(localEndPoint);

                Console.WriteLine("Server: {0} server socket bound to {1}", sockProtocol.ToString(), localEndPoint.ToString());

                if (sockProtocol == ProtocolType.Tcp)
                {
                    // If TCP socket, set the socket to listening
                    serverSocket.Listen(1);
                    Console.WriteLine("Server: Listen() is OK, I'm listening for connection buddy!");
                }
                else
                {
                    byte[] byteTrue = new byte[4];

                    // Set the SIO_UDP_CONNRESET ioctl to true for this UDP socket. If this UDP socket
                    //    ever sends a UDP packet to a remote destination that exists but there is
                    //    no socket to receive the packet, an ICMP port unreachable message is returned
                    //    to the sender. By default, when this is received the next operation on the
                    //    UDP socket that send the packet will receive a SocketException. The native
                    //    (Winsock) error that is received is WSAECONNRESET (10054). Since we don't want
                    //    to wrap each UDP socket operation in a try/except, we'll disable this error
                    //    for the socket with this ioctl call.
                    byteTrue[byteTrue.Length - 1] = 1;
                    serverSocket.IOControl(ServerSocket.SIO_UDP_CONNRESET, byteTrue, null);
                    Console.WriteLine("Server: IOControl() is OK...");
                }

                // Service clients in a loop
                while (true)
                {
                    if (sockProtocol == ProtocolType.Tcp)
                    {
                        // Wait for a client connection
                        clientSocket = serverSocket.Accept();
                        Console.WriteLine("Server: Accept() is OK...");
                        Console.WriteLine("Server: Accepted connection from: {0}", clientSocket.RemoteEndPoint.ToString());

                        // Receive the request from the client in a loop until the client shuts
                        //    the connection down via a Shutdown.
                        Console.WriteLine("Server: Preparing to receive using Receive()...");
                        while (true)
                        {
                            rc = clientSocket.Receive(receiveBuffer);

                            Console.WriteLine("Server: Read {0} bytes", rc);
                            if (rc == 0)
                            {
                                break;
                            }
                        }

                        // Send the indicated number of response messages
                        Console.WriteLine("Server: Preparing to send using Send()...");
                        for (int i = 0; i < sendCount; i++)
                        {
                            rc = clientSocket.Send(sendBuffer);
                            Console.WriteLine("Server: Sent {0} bytes", rc);
                        }

                        // Shutdown the client connection
                        clientSocket.Shutdown(SocketShutdown.Send);
                        Console.WriteLine("Server: Shutdown() is OK...");
                        clientSocket.Close();
                        Console.WriteLine("Server: Close() is OK...");
                    }
                    else
                    {
                        castSenderAddress = (EndPoint)senderAddress;

                        // Receive the initial request from the client
                        rc = serverSocket.ReceiveFrom(receiveBuffer, ref castSenderAddress);
                        Console.WriteLine("Server: ReceiveFrom() is OK...");
                        senderAddress = (IPEndPoint)castSenderAddress;
                        Console.WriteLine("Server: Received {0} bytes from {1}", rc, senderAddress.ToString());

                        // Send the response to the client the requested number of times
                        for (int i = 0; i < sendCount; i++)
                        {
                            try {
                                rc = serverSocket.SendTo(sendBuffer, senderAddress);
                                Console.WriteLine("Server: SendTo() is OK...");
                            } catch {
                                // If the sender's address is being spoofed we may get an error when sending
                                //    the response. You can test this by using IPv6 and using the RawSocket
                                //    sample to spoof a UDP packet with an invalid link local source address.
                                continue;
                            }
                            Console.WriteLine("Server: Sent {0} bytes to {1}", rc, senderAddress.ToString());
                        }

                        // Send several zero byte datagrams to indicate to client that no more data
                        //    will be sent from the server. Multiple packets are sent since UDP
                        //    is not guaranteed and we want to try to make an effort the client
                        //    gets at least one.
                        Console.WriteLine("Server: Preparing to send using SendTo(), on the way do sleeping, Sleep(250)...");
                        for (int i = 0; i < 3; i++)
                        {
                            serverSocket.SendTo(sendBuffer, 0, 0, SocketFlags.None, senderAddress);
                            // Space out sending the zero byte datagrams a bit. UDP is unreliable and
                            //   the local stack can even drop them before even hitting the wire!
                            System.Threading.Thread.Sleep(250);
                        }
                    }
                }
            } catch (SocketException err) {
                Console.WriteLine("Server: Socket error occurred: {0}", err.Message);
            } finally {
                // Close the socket if necessary
                if (serverSocket != null)
                {
                    Console.WriteLine("Server: Closing using Close()...");
                    serverSocket.Close();
                }
            }
        }
Exemple #54
0
 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _socket = new Java.Net.Socket();
 }
Exemple #55
0
        public static void Create(AddressFamily addressFamily = AddressFamily.InterNetwork, SocketType socketType = SocketType.Stream, ProtocolType protocolType = ProtocolType.Tcp)
        {
            if (Created)
            {
                return;
            }

            mDefaultAddressFamily = addressFamily;
            mDefaultSocketType    = socketType;
            mDefaultProtocolType  = protocolType;

            CConsole.StatusLine("Creating {0} Sockets...", mInitialCapacity);

            mFreeSockets = new Queue <Socket>(mInitialCapacity);
            LoadPool(addressFamily, socketType, protocolType);

            Created = true;
        }
Exemple #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SocketProxy"/> class.
 /// </summary>
 /// <param name="addressFamily">The address family.</param>
 /// <param name="socketType">Type of the socket.</param>
 /// <param name="protocolType">Type of the protocol.</param>
 internal SocketProxy(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _socket = new Socket(addressFamily, socketType, protocolType);
 }
Exemple #57
0
 internal static extern IntPtr socket(
     [In] AddressFamily addressFamily,
     [In] SocketType socketType,
     [In] ProtocolType protocolType
     );
Exemple #58
0
 /// <summary>
 /// 构造函数、参数选填。当不填写参数,采用默认值:
 /// AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp
 /// </summary>
 /// <param name="addressFamily">当不填写参数,采用默认值:AddressFamily.InterNetwork</param>
 /// <param name="soketType">当不填写参数,采用默认值:SocketType.Stream</param>
 /// <param name="protocolType">当不填写参数,采用默认值:ProtocolType.Tcp</param>
 public ClientSocket(AddressFamily addressFamily = AddressFamily.InterNetwork,
                     SocketType soketType        = SocketType.Stream,
                     ProtocolType protocolType   = ProtocolType.Tcp)
 {
     m_clientSocket = new Socket(addressFamily, soketType, protocolType);
 }
Exemple #59
0
 public SocketListener(SocketType type, IPEndPoint host, Action <Byte[], WritebackHandle> dataReceivedCallback)
     : this(type, host, () => { return(new BinaryComm(dataReceivedCallback)); })
 {
 }
Exemple #60
0
 public void Ctor_Success(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     using (new Socket(addressFamily, socketType, protocolType))
     {
     }
 }