// Initialize this object with a new TCP socket, optionally bind
	// to a local end-point, and optionally connect to a remote
	// end-point.  If anything fails, the object will be left in a
	// clean state, with the socket handle closed.
	private void Initialize(IPEndPoint localEP, IPEndPoint remoteEP,
							AddressFamily family)
			{
				client = new Socket
					(family, SocketType.Stream, ProtocolType.Tcp);
				stream = null;
				active = false;
				try
				{
					if(localEP != null)
					{
						client.Bind(localEP);
					}
					if(remoteEP != null)
					{
						client.Connect(remoteEP);
						active = true;
					}
				}
				catch(SocketException)
				{
					// We weren't able to bind or connect, so clean up the
					// socket on our way back up the stack.
					client.Close();
					client = null;
					throw;
				}
			}
Example #2
0
        public UdpSocket(AddressFamily addressFamily)
            : base(addressFamily, SocketType.Dgram, ProtocolType.Udp)
        {
            // Get the External Interface, save it for future use
            //IPAddress externalInterface = Utility.GetLocalRoutingInterface(endPoint.Address);

        }
 public NetworkDevice(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, EndPoint endPoint)
 {
     _AddressFamily = addressFamily;
     _SocketType = socketType;
     _ProtocolType = protocolType;
     _EndPoint = endPoint;
 }
Example #4
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);
 }
Example #5
0
 private static Socket GetDisposedSocket(AddressFamily addressFamily = AddressFamily.InterNetwork)
 {
     using (var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp))
     {
         return socket;
     }
 }
 internal static void CheckFamilyUnspecified(AddressFamily family)
 {
     if (((family != AddressFamily.InterNetwork) && (family != AddressFamily.InterNetworkV6)) && (family != AddressFamily.Unspecified))
     {
         throw new ArgumentException(SR.GetString("net_invalidversion"), "family");
     }
 }
        /// <devdoc>
        ///    <para>
        ///       Constructor for an IPv6 Address with a specified Scope.
        ///    </para>
        /// </devdoc>
        public IPAddress(byte[] address,long scopeid) {

            if (address==null) {
                throw new ArgumentNullException("address");
            }

            if(address.Length != IPv6AddressBytes){
                throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "address");
            }

            m_Family = AddressFamily.InterNetworkV6;

            for (int i = 0; i < NumberOfLabels; i++) {
                m_Numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
            }

            //
            // Consider: Since scope is only valid for link-local and site-local
            //           addresses we could implement some more robust checking here
            //
            if ( scopeid < 0 || scopeid > 0x00000000FFFFFFFF ) {
                throw new ArgumentOutOfRangeException("scopeid");
            }

            m_ScopeId = scopeid;
        }
Example #8
0
        // Creates a new instance of the UdpClient class that communicates on the
        // specified port number.
        public UdpClient(int port, AddressFamily family)
        {
            // Validate input parameters.
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException("port");
            }

            // Validate the address family.
            if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException(SR.net_protocol_invalid_family, "family");
            }

            IPEndPoint localEP;
            _family = family;

            if (_family == AddressFamily.InterNetwork)
            {
                localEP = new IPEndPoint(IPAddress.Any, port);
            }
            else
            {
                localEP = new IPEndPoint(IPAddress.IPv6Any, port);
            }

            CreateClientSocket();

            _clientSocket.Bind(localEP);
        }
        /// <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();

        }
Example #10
0
        public DnsEndPoint(string host, int port, AddressFamily addressFamily)
        {
            if(host == null) {
                throw new ArgumentNullException("host");
            }

            if (String.IsNullOrEmpty(host)) {
                throw new ArgumentException(SR.GetString(SR.net_emptystringcall, "host"));
            }

            if(port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) {
                throw new ArgumentOutOfRangeException("port");
            }

            if (addressFamily != AddressFamily.InterNetwork &&
                addressFamily != AddressFamily.InterNetworkV6 &&
                addressFamily != AddressFamily.Unspecified)
            {
                throw new ArgumentException(SR.GetString(SR.net_sockets_invalid_optionValue_all), "addressFamily");
            }

            m_Host = host;
            m_Port = port;
            m_Family = addressFamily;
        }
 public UdpClient(int port, AddressFamily family)
 {
     IPEndPoint point;
     this.m_Buffer = new byte[0x10000];
     this.m_Family = AddressFamily.InterNetwork;
     if (!ValidationHelper.ValidateTcpPort(port))
     {
         throw new ArgumentOutOfRangeException("port");
     }
     if ((family != AddressFamily.InterNetwork) && (family != AddressFamily.InterNetworkV6))
     {
         throw new ArgumentException(SR.GetString("net_protocol_invalid_family"), "family");
     }
     this.m_Family = family;
     if (this.m_Family == AddressFamily.InterNetwork)
     {
         point = new IPEndPoint(IPAddress.Any, port);
     }
     else
     {
         point = new IPEndPoint(IPAddress.IPv6Any, port);
     }
     this.createClientSocket();
     this.Client.Bind(point);
 }
Example #12
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;
        }
 public SocketManager(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _addressFamily = addressFamily;
     _socketType = socketType;
     _protocolType = protocolType;
     _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
		private IntPtr Socket_internal(AddressFamily family,
		SocketType type,
		ProtocolType proto,
		out int error)
		{
			throw new System.NotImplementedException();
		}
        public void TestAddressFamilyObsolete(bool ipv6, AddressFamily addressFamily)
        {
#pragma warning disable 618
            var settings = new MongoServerSettings { IPv6 = ipv6 };
            Assert.AreEqual(addressFamily, settings.AddressFamily);
#pragma warning restore
        }
Example #16
0
        public TcpClient(AddressFamily addressFamily)
        {
            autoResetEvent = new AutoResetEvent(false);

            Client = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
            networkStream = new NetworkStream(Client);
        }
        private static bool IsProtocolSupported(AddressFamily af)
        {
            int family;
            switch (af)
            {
                case AddressFamily.InterNetwork:
                    family = Interop.libc.AF_INET;
                    break;
                case AddressFamily.InterNetworkV6:
                    family = Interop.libc.AF_INET6;
                    break;
                default:
                    Debug.Fail("Invalid address family: " + af.ToString());
                    throw new ArgumentException("af");
            }

            int socket = -1;
            try
            {
                socket = Interop.libc.socket(family, Interop.libc.SOCK_DGRAM, 0);
                if (socket == -1)
                {
                    return Interop.Sys.GetLastError() != Interop.Error.EAFNOSUPPORT;
                }
                return true;
            }
            finally
            {
                if (socket != -1)
                {
                    Interop.Sys.Close(socket);
                }
            }
        }
        /// <devdoc>
        ///    <para>
        ///       Creates a new instance of the UdpClient class that communicates on the
        ///       specified port number.
        ///    </para>
        /// </devdoc>
        public UdpClient(int port,AddressFamily family) {
            //
            // parameter validation
            //
            if (!ValidationHelper.ValidateTcpPort(port)) {
                throw new ArgumentOutOfRangeException("port");
            }
            //
            // Validate the address family
            //
            if ( family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6 ) {
                throw new ArgumentException(SR.GetString(SR.net_protocol_invalid_family), "family");
            }

            IPEndPoint localEP;
            m_Family = family;
             
            if ( m_Family == AddressFamily.InterNetwork ) {
                localEP = new IPEndPoint(IPAddress.Any, port);
            }
            else {
                localEP = new IPEndPoint(IPAddress.IPv6Any, port);
            }

            createClientSocket();

            Client.Bind(localEP);
        }
Example #19
0
 private Socket(AddressFamily family, SocketType type, ProtocolType proto, IntPtr native)
 {
     this.family = family;
     this.type = type;
     this.proto = proto;
     this.native = native;
 }
        public static unsafe void SetAddressFamily(byte[] buffer, AddressFamily family)
        {
            fixed (byte* rawAddress = buffer)
            {
                var sockaddr = (Interop.libc.sockaddr*)rawAddress;
                Interop.CheckBounds((byte*)sockaddr, buffer.Length, &sockaddr->sa_family);

                switch (family)
                {
                    case AddressFamily.Unspecified:
                        sockaddr->sa_family = Interop.libc.AF_UNSPEC;
                        break;

                    case AddressFamily.Unix:
                        sockaddr->sa_family = Interop.libc.AF_UNIX;
                        break;

                    case AddressFamily.InterNetwork:
                        sockaddr->sa_family = Interop.libc.AF_INET;
                        break;

                    case AddressFamily.InterNetworkV6:
                        sockaddr->sa_family = Interop.libc.AF_INET6;
                        break;

                    default:
                        Debug.Fail("Unsupported addres family");
                        throw new PlatformNotSupportedException();
                }
            }
        }
 internal SystemUdpStatistics(AddressFamily family){
     uint result = UnsafeNetInfoNativeMethods.GetUdpStatisticsEx(out stats, family);
     
     if (result != IpHelperErrors.Success) {
         throw new NetworkInformationException((int)result);
     }
 }
Example #22
0
 public UdpClient(int port, AddressFamily family)
 {
     IPEndPoint point;
     this.family = AddressFamily.InterNetwork;
     if ((family != AddressFamily.InterNetwork)
      //   && (family != AddressFamily.InterNetworkV6)
         )
     {
         throw new ArgumentException("Family must be InterNetwork or InterNetworkV6", "family");
     }
     if ((port < 0) || (port > 65535))
     {
         throw new ArgumentOutOfRangeException("port");
     }
     this.family = family;
       //  if (family == AddressFamily.InterNetwork)
     {
         point = new IPEndPoint(IPAddress.Any, port);
     }
     //else
     //{
     //    point = new IPEndPoint(IPAddress.IPv6Any, port);
     //}
     this.InitSocket(point);
 }
        /// <param name="ipRangeStr">
        /// e.g)
        /// "10.23.0.0/24",
        /// "127.0.0.1" (equals to "127.0.0.1/32"),
        /// "2001:0db8:bd05:01d2:288a:1fc0:0001:0000/16",
        /// "::1" (equals to "::1/128")
        /// </param>
        public IPAddressRange(string ipRangeString)
        {
            if (string.IsNullOrEmpty(ipRangeString))
                throw new InvalidOperationException("IP Address is null or empty.");

            var vals = ipRangeString.Split('/');
            IPAddress ipAddr;
            if (!IPAddress.TryParse(vals[0], out ipAddr))
                throw new InvalidOperationException(string.Format("IP Address({0}) is invalid format.", ipRangeString));

            _addressFamily = ipAddr.AddressFamily;
            if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
                throw new InvalidOperationException(string.Format("IP Address({0}) is not ip4 or ip6 address famiry.", ipRangeString));

            var maxMaskRange = _addressFamily == AddressFamily.InterNetwork ? 32 : 128;
            int maskRange;
            if (vals.Length > 1)
            {
                if (!int.TryParse(vals[1], out maskRange) || maskRange < 0 || maskRange > maxMaskRange)
                    throw new InvalidOperationException(string.Format("IP Address({0}) is invalid range.", ipRangeString));
            }
            else
                maskRange = maxMaskRange;

            _netowrkAddressBytes = ipAddr.GetAddressBytes();
            _subnetMaskBytes = Enumerable.Repeat<byte>(0xFF, _netowrkAddressBytes.Length).ToArray();

            for (int i = 0; i < (maxMaskRange - maskRange); i++)
                _subnetMaskBytes[_subnetMaskBytes.Length - 1 - i / 8] -= (byte)(1 << (i % 8));
        }
Example #24
0
 public RawSocket(AddressFamily family, SocketProvider provider)
 {
     m_rawsock = new Socket(family, SocketType.Raw, ProtocolType.IP);
     m_rawsock.Blocking = false;
     m_Provider = provider;
     m_ReceivedData = new AsyncCallback(OnReceive);
 }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
           
           // Timer a = new Timer();
//
            //Ping pingSender = new Ping();
            ////for(int i=0;i<30;i++)
            ////{
            //  //  MessageBox.Show(adr);
               String adr ="172.16.16.10";
                IPAddress address = IPAddress.Parse(adr);
            //  //  pingSender.SendAsync(address,250,new PingOptions(5,true));
            // pingSender.SendAsync(address, 250);
           
            //pingSender.PingCompleted += (a, b) =>
            //{
            //    if (b.Reply.Status == IPStatus.Success)
            //    {
            //        MessageBox.Show(b.ToString());
            //    }
            //    else
            //    {
            //        MessageBox.Show("failed");
            //    }

            //};
            //PingReply reply = await pingSender.SendPingAsync(address);

            //if (reply.Status == IPStatus.Success)
            //{
            //    ListBox1.Items.Add(adr);
            //}
            //else
            //{
            //    ListBox2.Items.Add("Failed "+adr); // MessageBox.Show("falied" + adr);
            //}
            //}  
            AddressFamily d=new AddressFamily();

            try
            {
                Ping s=new Ping();
                var a= s.SendPingAsync(address).GetAwaiter();
               a.OnCompleted(() => MessageBox.Show(a.GetResult().Status.ToString()));
               //UdpClient udp=new UdpClient(8080);
               // udp.Connect(address,8080);
               // var a=new byte[]{1,2};
               // await udp.SendAsync(a,44);
               // TcpClient tcp = new TcpClient();
                //await tcp.ConnectAsync(adr, 8080);
               // MessageBox.Show(adr);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
Example #26
0
        public DnsEndPoint(string host, int port, AddressFamily addressFamily)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            if (String.IsNullOrEmpty(host))
            {
                throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(host)));
            }

            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            if (addressFamily != AddressFamily.InterNetwork &&
                addressFamily != AddressFamily.InterNetworkV6 &&
                addressFamily != AddressFamily.Unspecified)
            {
                throw new ArgumentException(SR.net_sockets_invalid_optionValue_all, nameof(addressFamily));
            }

            _host = host;
            _port = port;
            _family = addressFamily;
        }
Example #27
0
			public void Reset (Socket socket, IPEndPoint ip)
			{
				this.addressFamily = socket.AddressFamily;
				this.socketType = socket.SocketType;
				this.protocolTtype = socket.ProtocolType;
				this.RemoteEndPoint = ip;
			}
Example #28
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;
        }
Example #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Address"/> class.
 /// </summary>
 /// <param name="addressFamily">The IP address family</param>
 /// <param name="address">The IP address</param>
 /// <param name="port">The port</param>
 public Address(AddressFamily addressFamily, string address, int port)
 {
     _isEnhanced = true;
     AddressFamily = addressFamily;
     IpAddress = address;
     IpPort = port;
 }
Example #30
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();
 }
Example #31
0
        /// <summary>
        /// 连接指定的服务器。
        /// </summary>
        public bool Connect(Server server, AddressFamily addressFamily = AddressFamily.InterNetwork)
        {
            _networkAddressFamily = addressFamily;

            if (_socket != null)
            {
                _socket.Close();
                _socket = null;
            }

            if (server == Server.Null ||
                server == Server.CServer)
            {
                // 其他的服务器就不用连接了。
                return(false);
            }

            var hServerAddress = _hServerAddress.Read();
            var gServerAddress = _gServerAddress.Read();

            string host = "";
            int    port = 0;

            switch (server)
            {
            case Server.PServer:
                host = GetHost();
                port = GetPort();
                break;

            case Server.HServer:
                host = hServerAddress;
                port = 11122;
                break;

            case Server.GServer:

                if (gServerAddress == null)
                {
                    MyLog.ErrorWithFrame(
                        name,
                        string.Format("GameServer Address Error ")
                        );

                    return(false);
                }

                host = gServerAddress.Ip;
                port = gServerAddress.Port;
                break;

            default:
                break;
            }

            MyLog.InfoWithFrame(
                name,
                string.Format("Connect gate server: {0}:{1}",
                              host,
                              port)
                );

#if UNITY_IOS
            var ios = _context.GetIosSDK();

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                host = ios.GetIpV6(host);
                MyLog.InfoWithFrame(name, string.Format("convert to ipv6: {0}", host));
            }
#endif

            if (string.IsNullOrEmpty(host))
            {
                return(false);
            }

            var socketFactory = _context.GetSocketFactory();

            _socket = socketFactory.CreateSocket();
            return(_socket.Connect(host, port, server, addressFamily));
        }
 public SocketDatagramChannel(AddressFamily addressFamily)
     : this(new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp))
 {
 }
Example #33
0
 internal RedisSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType)
 {
 }
Example #34
0
        /// <summary>创建Tcp/Udp、IPv4/IPv6服务</summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        /// <param name="protocol"></param>
        /// <param name="family"></param>
        /// <returns></returns>
        protected static ISocketServer[] CreateServer(IPAddress address, Int32 port, NetType protocol, AddressFamily family)
        {
            switch (protocol)
            {
            case NetType.Tcp:
                return(CreateServer <TcpServer>(address, port, family));

            case NetType.Http:
            case NetType.WebSocket:
                var ss = CreateServer <TcpServer>(address, port, family);
                foreach (TcpServer item in ss)
                {
                    item.EnableHttp = true;
                }
                return(ss);

            case NetType.Udp:
                return(CreateServer <UdpServer>(address, port, family));

            case NetType.Unknown:
            default:
                var list = new List <ISocketServer>();

                // 其它未知协议,同时用Tcp和Udp
                list.AddRange(CreateServer <TcpServer>(address, port, family));
                list.AddRange(CreateServer <UdpServer>(address, port, family));

                return(list.ToArray());
            }
        }
Example #35
0
        /// <summary>同时添加指定端口的IPv4和IPv6服务器,如果协议不是指定的Tcp或Udp,则同时添加Tcp和Udp服务器</summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        /// <param name="protocol"></param>
        /// <param name="family"></param>
        /// <returns></returns>
        public virtual Int32 AddServer(IPAddress address, Int32 port, NetType protocol = NetType.Unknown, AddressFamily family = AddressFamily.Unspecified)
        {
            var list  = CreateServer(address, port, protocol, family);
            var count = 0;

            foreach (var item in list)
            {
                AttachServer(item);

                count++;
            }
            return(count);
        }
Example #36
0
 /// <summary>
 /// Creates a new <see cref="TcpSocket"/>.
 /// </summary>
 /// <param name="family">The AddressFamily of the IP.</param>
 public TcpSocket(AddressFamily family)
     : base(CreateSocket(ref family))
 {
     m_family = family;
 }
Example #37
0
        private static Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);

            return(socket);
        }
Example #38
0
 public SocketClient(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _socket = new Socket(addressFamily, socketType, protocolType);
 }
Example #39
0
 public override bool IsAddressFamilySupported(AddressFamily addresFamily)
 {
     return(true);
 }
Example #40
0
 public SocketManager(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType)
 {
 }
Example #41
0
 public CFSocket(AddressFamily family, SocketType type, ProtocolType proto)
     : this(family, type, proto, CFRunLoop.Current)
 {
 }
 public PreferredAddressFamilyComparer(AddressFamily preferred)
 {
     _preferred = preferred;
 }
Example #43
0
        public double m_dCWnd;         // congestion window size, congestion control

        public InfoBlock(IPAddress address)
        {
            m_iIPversion = address.AddressFamily;
            ConvertIPAddress.ToUintArray(address, ref m_piIP);
        }
Example #44
0
 public CFSocket(AddressFamily family, SocketType type, ProtocolType proto, CFRunLoop loop)
     : this(CFSocketSignature.AddressFamilyToInt(family),
            CFSocketSignature.SocketTypeToInt(type),
            CFSocketSignature.ProtocolToInt(proto), loop)
 {
 }
        /// <summary>
        /// Configures the SSDP part of the given endpoint <paramref name="config"/>.
        /// Starts the SSDP UDP listener client for the given network endpoint.
        /// </summary>
        /// <param name="config">The endpoint configuration which should be started.</param>
        public void StartSSDPEndpoint(EndpointConfiguration config)
        {
            IPAddress     address = config.EndPointIPAddress;
            AddressFamily family  = address.AddressFamily;

            config.SSDPMulticastAddress = NetworkHelper.GetSSDPMulticastAddressForInterface(address);
            config.SSDPSearchPort       = UPnPConsts.DEFAULT_SSDP_SEARCH_PORT;

            // Multicast socket - used for sending and receiving multicast messages
            Socket socket = new Socket(family, SocketType.Dgram, ProtocolType.Udp);

            config.SSDP_UDP_MulticastReceiveSocket = socket;
            try
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                NetworkHelper.BindAndConfigureSSDPMulticastSocket(socket, address);
                StartReceive(new UDPAsyncReceiveState <EndpointConfiguration>(config, UPnPConsts.UDP_SSDP_RECEIVE_BUFFER_SIZE, socket));
            }
            catch (Exception) // SocketException, SecurityException
            {
                UPnPConfiguration.LOGGER.Info("SSDPServerController: Unable to bind to multicast address(es) for endpoint '{0}'",
                                              NetworkHelper.IPAddrToString(address));
            }

            // Unicast sender and receiver socket - used for receiving unicast M-SEARCH queries and sending M-SEARCH responses
            socket = new Socket(family, SocketType.Dgram, ProtocolType.Udp);
            config.SSDP_UDP_UnicastSocket = socket;
            try
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                try
                {
                    // Try to bind our unicast receiver socket to the default SSDP port
                    socket.Bind(new IPEndPoint(address, config.SSDPSearchPort));
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode != SocketError.AddressAlreadyInUse)
                    {
                        throw;
                    }
                    // If binding to the default SSDP port doesn't work, try a random port...
                    socket.Bind(new IPEndPoint(address, 0));
                    // ... which will be stored in the SSDPSearchPort variable which will be used for the SEARCHPORT.UPNP.ORG SSDP header.
                    config.SSDPSearchPort = ((IPEndPoint)socket.LocalEndPoint).Port;
                }
                UPnPConfiguration.LOGGER.Info("UPnPServerController: SSDP enabled for IP endpoint '{0}', search port is {1}",
                                              NetworkHelper.IPAddrToString(address), config.SSDPSearchPort);
                // The following is necessary to retrieve the remote IP address when we receive SSDP packets
                if (family == AddressFamily.InterNetwork)
                {
                    try
                    {
                        // Receiving options
                        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
                        // Sending options
                        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
                                               UPnPConfiguration.SSDP_UDP_TTL_V4);
                    }
                    catch (SocketException e)
                    {
                        UPnPConfiguration.LOGGER.Warn("GENAServerController: Could not set IPv4 options", e);
                    }
                }
                else
                {
                    try
                    {
                        // Receiving options
                        socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
                        // Sending options
                        socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.HopLimit,
                                               UPnPConfiguration.SSDP_UDP_HOP_LIMIT_V6);
                    }
                    catch (SocketException e)
                    {
                        UPnPConfiguration.LOGGER.Warn("GENAServerController: Could not set IPv6 options", e);
                    }
                }
                StartReceive(new UDPAsyncReceiveState <EndpointConfiguration>(config, UPnPConsts.UDP_SSDP_RECEIVE_BUFFER_SIZE, socket));
            }
            catch (Exception) // SocketException, SecurityException
            {
                UPnPConfiguration.LOGGER.Info("SSDPServerController: Unable to bind to unicast address '{0}'",
                                              NetworkHelper.IPAddrToString(address));
            }
        }
Example #46
0
 public SocketAddress(AddressFamily family) : this(family, MaxSize)
 {
 }
Example #47
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>
 /// <exception cref="SocketException">
 ///     The combination of addressFamily, socketType, and protocolType results in an invalid
 ///     socket.
 /// </exception>
 /// <exception cref="ArgumentNullException"><c>proxyUsername</c> is null.</exception>
 public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType,
                    string proxyUsername) : this(addressFamily, socketType, protocolType, proxyUsername, "")
 {
 }
Example #48
0
 public static void getIPType(String serverIp, String serverPorts, out String newServerIp, out AddressFamily mIPType)
 {
     mIPType     = AddressFamily.InterNetwork;
     newServerIp = serverIp;
     try
     {
         string mIPv6 = GetIPv6(serverIp, serverPorts);
         if (!string.IsNullOrEmpty(mIPv6))
         {
             string[] m_StrTemp = System.Text.RegularExpressions.Regex.Split(mIPv6, "&&");
             if (m_StrTemp != null && m_StrTemp.Length >= 2)
             {
                 string IPType = m_StrTemp[1];
                 if (IPType == "ipv6")
                 {
                     newServerIp = m_StrTemp[0];
                     mIPType     = AddressFamily.InterNetworkV6;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Debug.LogError("getIPType err : " + ex.Message + "\n" + ex.StackTrace);
     }
 }
Example #49
0
 public TestConnection(int port, AddressFamily addressFamily)
     : this(CreateConnectedLoopbackSocket(port, addressFamily), ownsSocket : true)
 {
 }
Example #50
0
 public void GetIPType(string serverIp, string serverPorts, out string newServerIp, out AddressFamily newIPType)
 {
     newIPType   = AddressFamily.InterNetwork;
     newServerIp = serverIp;
     try
     {
         string mIPv6 = GetIPv6(serverIp, serverPorts);
         if (!string.IsNullOrEmpty(mIPv6))
         {
             string[] m_StrTemp = System.Text.RegularExpressions.Regex.Split(mIPv6, "&&");
             if (m_StrTemp != null && m_StrTemp.Length >= 2)
             {
                 string IPType = m_StrTemp[1];
                 if (IPType == "ipv6")
                 {
                     newServerIp = m_StrTemp[0];
                     newIPType   = AddressFamily.InterNetworkV6;
                 }
             }
         }
     }
     catch (Exception e)
     {
         DebugUtil.Log("GetIPv6 error:" + e);
     }
 }
Example #51
0
 internal static unsafe partial uint NotifyStableUnicastIpAddressTable(
     AddressFamily addressFamily,
     out SafeFreeMibTable table,
Example #52
0
 public static extern IntPtr WSASocket(AddressFamily af, SocketType type, ProtocolType protocol, IntPtr lpProtocolInfo, uint g, int dwFlags);
Example #53
0
 internal static unsafe partial uint GetUdpStatisticsEx(MibUdpStats *statistics, AddressFamily family);
Example #54
0
 /// <summary>
 /// 初始化,给出服务器端口和ip地址
 /// </summary>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 /// <param name="address"></param>
 public void Initialize(string ip, int port, AddressFamily address = AddressFamily.InterNetwork)
 {
     this.IP      = ip;
     this.Port    = port;
     this.Address = address;
 }
 public ClientSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType)
 {
 }
Example #56
0
 // TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
 internal static extern uint GetIcmpStatisticsEx(out MibIcmpInfoEx statistics, AddressFamily family);
Example #57
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>
 /// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
 public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : this(addressFamily, socketType, protocolType, "")
 {
 }
Example #58
0
 internal static unsafe partial uint GetAdaptersAddresses(
     AddressFamily family,
     uint flags,
     IntPtr pReserved,
     IntPtr adapterAddresses,
     uint *outBufLen);
Example #59
0
        public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix(AddressFamily addressFamily)
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync(addressFamily);

            if (localIpAddress == null)
            {
                // No local address for given address family.
                return;
            }

            byte[] buffer = TestSettings.PayloadAsBytes;
            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);

                // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
                if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
                {
                    Assert.Equal(buffer, pingReply.Buffer);
                }
                else
                {
                    Assert.Equal(Array.Empty <byte>(), pingReply.Buffer);
                }
            });
        }
Example #60
0
 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _socket = new System.Net.Sockets.Socket(addressFamily, socketType, protocolType);
 }