Example #1
0
        public static IPEndPoint QueryRoutingInterface(string remoteAddress, int port)
        {
            var remoteEndPoint  = new IPEndPoint(IPAddress.Parse(remoteAddress), port);
            var socket          = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var address         = remoteEndPoint.Serialize();
            var remoteAddrBytes = new byte[address.Size];

            for (int i = 0; i < address.Size; i++)
            {
                remoteAddrBytes[i] = address[i];
            }

            var outBytes = new byte[remoteAddrBytes.Length];

            socket.IOControl(
                IOControlCode.RoutingInterfaceQuery,
                remoteAddrBytes,
                outBytes);

            for (int i = 0; i < address.Size; i++)
            {
                address[i] = outBytes[i];
            }

            return((IPEndPoint)remoteEndPoint.Create(address));
        }
        /// <summary>
        /// Bind the local and remote IPEndPoint.
        /// for tcp: map from lsp dll tcp endpoint to the real tcp endpoint
        /// for udp: map from the real udp endpoint to lsp dll udp endpoint
        /// </summary>
        /// <param name="localEndpoint">Local server endpoint of sdk</param>
        /// <param name="srcEndPoint">the tcp/udp endpoint</param>
        /// <param name="mappedEndPoint">the tcp/udp endpoint </param>
        /// <param name="transportType">Tcp or Udp </param>
        internal void SetMappedIPEndPoint(IPEndPoint localEndpoint, IPEndPoint srcEndPoint,
                                          IPEndPoint mappedEndPoint, StackTransportType transportType)
        {
            if (disposed)
            {
                return;
            }

            Dictionary <string, IPEndPoint> endPointMap;

            IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);

            string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();

            if (sessionMap.ContainsKey(strKey))
            {
                endPointMap = sessionMap[strKey].endPoints;
            }
            else
            {
                return;
            }

            strKey = srcEndPoint.Serialize().ToString();
            endPointMap[strKey] = mappedEndPoint;

            //For tcp, each endpoint-to-endpoint pair has two records in the dictionary.
            if (transportType == StackTransportType.Tcp)
            {
                strKey = mappedEndPoint.Serialize().ToString();
                endPointMap[strKey] = srcEndPoint;
            }
        }
Example #3
0
        // Taken From: https://searchcode.com/codesearch/view/7464800/
        private static IPEndPoint QueryRoutingInterface(
            Socket socket,
            IPEndPoint remoteEndPoint)
        {
            SocketAddress address = remoteEndPoint.Serialize();

            byte[] remoteAddrBytes = new byte[address.Size];
            for (int i = 0; i < address.Size; i++)
            {
                remoteAddrBytes[i] = address[i];
            }

            byte[] outBytes = new byte[remoteAddrBytes.Length];
            socket.IOControl(
                IOControlCode.RoutingInterfaceQuery,
                remoteAddrBytes,
                outBytes);
            for (int i = 0; i < address.Size; i++)
            {
                address[i] = outBytes[i];
            }

            EndPoint ep = remoteEndPoint.Create(address);

            return((IPEndPoint)ep);
        }
        public void TestSocketAddress()
        {
            IPEndPoint    endPoint                = new IPEndPoint(new IPAddress(0), 1);
            SocketAddress socketAddress           = endPoint.Serialize();
            var           serializedSocketAddress = new SerializedSocketAddress(socketAddress);
            var           packet = new Packet {
                SerializedSocketAddress = serializedSocketAddress
            };

            var writer = new NetDataWriter();
            NetPacketProcessor processor = new NetPacketProcessor();

            SerializedSocketAddress.RegisterWith(processor);

            processor.Write(writer, packet);

            var    reader     = new NetDataReader(writer.CopyData());
            Packet readPacket = null;

            processor.Subscribe <Packet>(packet => readPacket = packet, () => new Packet());

            processor.ReadAllPackets(reader);

            Assert.IsNotNull(readPacket);
            Assert.AreEqual(serializedSocketAddress.SocketAddress, readPacket.SerializedSocketAddress.SocketAddress);
        }
Example #5
0
        public void ToString_ValidSocketAddress_ExpectedFormat()
        {
            IPEndPoint    ipLocalEndPoint = new IPEndPoint(IPAddress.Loopback, Convert.ToInt32("cafe", 16));
            SocketAddress socketAddress   = ipLocalEndPoint.Serialize();

            Assert.Equal("InterNetwork:16:{202,254,127,0,0,1,0,0,0,0,0,0,0,0}", socketAddress.ToString());
        }
Example #6
0
        public static IPEndPoint QueryRoutingInterface(Socket socket, IPEndPoint remoteEP)
        {
            ValidateHelper.CheckNullArgument("sock", socket);
            ValidateHelper.CheckNullArgument("remoteEP", remoteEP);

            SocketAddress socketAddress = remoteEP.Serialize();

            byte[] optionInValue = new byte[socketAddress.Size];

            for (int i = 0; i < socketAddress.Size; i++)
            {
                optionInValue[i] = socketAddress[i];
            }

            byte[] optionOutValue = new byte[optionInValue.Length];
            socket.IOControl(IOControlCode.RoutingInterfaceQuery, optionInValue, optionOutValue);

            for (int j = 0; j < socketAddress.Size; j++)
            {
                socketAddress[j] = optionOutValue[j];
            }

            IPEndPoint point = (IPEndPoint)remoteEP.Create(socketAddress);

            point.Port = ((IPEndPoint)socket.LocalEndPoint).Port;
            return(point);
        }
        /// <summary>
        /// Get the local IPEndPoint by remote IPEndPoint. The key is remote IPEndPoint.
        /// for tcp: map from lsp dll tcp endpoint to the real tcp endpoint
        /// for udp: map from the real udp endpoint to lsp dll udp endpoint
        /// </summary>
        /// <param name="localEndpoint">Local server endpoint of sdk</param>
        /// <param name="srcEndPoint">source endpoint</param>
        /// <param name="transportType">tcp or udp</param>
        /// <returns>Local LspClient socket</returns>
        internal IPEndPoint GetMappedIPEndPoint(IPEndPoint localEndpoint, IPEndPoint srcEndPoint, StackTransportType transportType)
        {
            if (disposed)
            {
                return(null);
            }

            Dictionary <string, IPEndPoint> endPointMap;

            IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);

            string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();

            if (sessionMap.ContainsKey(strKey))
            {
                endPointMap = sessionMap[strKey].endPoints;
            }
            else
            {
                return(null);
            }

            strKey = srcEndPoint.Serialize().ToString();
            if (endPointMap.ContainsKey(strKey))
            {
                return(endPointMap[strKey]);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Disconnect the remote EndPoint, and clean up the resources.
        /// </summary>
        /// <param name="localEndpoint">SDK listening endpoint</param>
        /// <param name="remoteEndpoint">the endpoint of real remote client</param>
        /// <param name="transportType">Tcp or Udp</param>
        internal void Disconnect(IPEndPoint localEndpoint, IPEndPoint remoteEndpoint,
                                 StackTransportType transportType)
        {
            if (disposed)
            {
                return;
            }

            IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);

            string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();

            if (sessionMap.ContainsKey(strKey))
            {
                Dictionary <string, IPEndPoint> endPointMap =
                    sessionMap[strKey].endPoints;
                strKey = remoteEndpoint.Serialize().ToString();
                if (transportType == StackTransportType.Udp)
                {
                    endPointMap.Remove(strKey);
                }
                else
                {
                    //For tcp, each endpoint-to-endpoint pair has two records in the dictionary.
                    IPEndPoint mappedEndpoint = endPointMap[strKey];
                    endPointMap.Remove(strKey);
                    endPointMap.Remove(mappedEndpoint.Serialize().ToString());
                }
            }
        }
Example #9
0
 public override SocketAddress Serialize()
 {
     if (mIsDirty)
     {
         mSocketAddress = mIPEndPoint.Serialize();
         mIsDirty       = false;
     }
     return(mSocketAddress);
 }
Example #10
0
        internal ConnectRequestResult ProcessConnectRequest(NetConnectRequestPacket connRequest)
        {
            //current or new request
            switch (_connectionState)
            {
            //P2P case
            case ConnectionState.Outgoing:
                //fast check
                if (connRequest.ConnectionTime < _connectTime)
                {
                    return(ConnectRequestResult.P2PLose);
                }
                //slow rare case check
                else if (connRequest.ConnectionTime == _connectTime)
                {
                    var remoteBytes = EndPoint.Serialize();
                    var localBytes  = connRequest.TargetAddress;
                    for (int i = remoteBytes.Size - 1; i >= 0; i--)
                    {
                        byte rb = remoteBytes[i];
                        if (rb == localBytes[i])
                        {
                            continue;
                        }
                        if (rb < localBytes[i])
                        {
                            return(ConnectRequestResult.P2PLose);
                        }
                    }
                }
                break;

            case ConnectionState.Connected:
                //Old connect request
                if (connRequest.ConnectionTime == _connectTime)
                {
                    //just reply accept
                    NetManager.SendRaw(_connectAcceptPacket, EndPoint);
                }
                //New connect request
                else if (connRequest.ConnectionTime > _connectTime)
                {
                    return(ConnectRequestResult.Reconnection);
                }
                break;

            case ConnectionState.Disconnected:
            case ConnectionState.ShutdownRequested:
                if (connRequest.ConnectionTime >= _connectTime)
                {
                    return(ConnectRequestResult.NewConnection);
                }
                break;
            }
            return(ConnectRequestResult.None);
        }
Example #11
0
        public static void fSocketAddress()
        {
            IPAddress  ipAddr1    = IPAddress.Parse("127.0.0.1");
            IPAddress  ipAddr2    = IPAddress.Parse("::1");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr1, 80);

            SocketAddress SocketAddr = ipEndPoint.Serialize();

            MessageBox.Show(SocketAddr.ToString());
        }
        static void Main(string[] args)
        {
            IPAddress     ipAddress       = Dns.GetHostEntry("localhost").AddressList[0];
            IPEndPoint    ipLocalEndPoint = new IPEndPoint(ipAddress, 11000);
            SocketAddress socketAddress   = ipLocalEndPoint.Serialize();

            Console.WriteLine("Contents of the socketAddress are: " + socketAddress.ToString());
            Console.WriteLine("The address family of the socketAddress is: " + socketAddress.Family.ToString());
            Console.WriteLine("The size of the underlying buffer is: " + socketAddress.Size.ToString());
        }
Example #13
0
    public static void Main()
    {
        IPAddress  test1 = IPAddress.Parse("192.168.1.1");
        IPEndPoint ie    = new IPEndPoint(test1, 8000);

        ie.Port = 8000;
        SocketAddress sa = ie.Serialize();

        Console.WriteLine("The SocketAddress is: {0}", sa.ToString());
    }
Example #14
0
        public static void SerializeCreate_Compare_Equal()
        {
            //Serializing an IPEndPoint from a SocketAddress should produce the same output as creating one from a SocketAddress
            IPEndPoint    ep = new IPEndPoint(testIpV41, 500);
            SocketAddress sa = ep.Serialize();

            EndPoint ep2 = ep.Create(sa);

            Assert.Equal(ep, ep2);
        }
        private static byte[] ToArray(this IPEndPoint ep)
        {
            var addr = ep.Serialize();

            byte[] buffer = new byte[addr.Size];
            for (int i = 0; i < addr.Size; ++i)
            {
                buffer[i] = addr[i];
            }
            return(buffer);
        }
 /// <summary>
 /// Map the intercepted IPEndPoint to the LspSession.
 /// </summary>
 /// <param name="index">Intercepted IPEndPoint. </param>
 /// <param name="transportType">Tcp or Udp</param>
 /// <returns>Mapped LspSession</returns>
 private LspSessionInfoCollection this[IPEndPoint index, StackTransportType transportType]
 {
     get
     {
         string strKey = transportType.ToString() + index.Serialize().ToString();
         if (sessionMap.ContainsKey(strKey))
         {
             return(sessionMap[strKey]);
         }
         else
         {
             return(null);
         }
     }
     set
     {
         string strKey = transportType.ToString() + index.Serialize().ToString();
         sessionMap[strKey] = value;
     }
 }
Example #17
0
        private byte[] MakeSocketAddr(IPEndPoint ep)
        {
            var saddr = ep.Serialize();

            byte[] data = new byte[saddr.Size];
            for (int i = 0; i < saddr.Size; i++)
            {
                data[i] = saddr[i];
            }
            return(data);
        }
        /// <summary>
        /// Intercept the ip traffic in a designated address. All the traffic will be sent to sdkListeningIpAddress.
        /// </summary>
        /// <param name="transportType">TCP or UDP . </param>
        /// <param name="isBlocking">Whether this request is a blocking request.</param>
        /// <param name="interceptedEndPoint">The intercepted IP/Port of the windows service . </param>
        internal void InterceptTraffic(StackTransportType transportType, bool isBlocking, IPEndPoint interceptedEndPoint)
        {
            if (disposed)
            {
                return;
            }

            string strKey = transportType.ToString() + interceptedEndPoint.Serialize().ToString();

            endPointsToHook[strKey] = isBlocking;
        }
Example #19
0
        public void WriteIPEndPoint(IPEndPoint value)
        {
            SocketAddress socketAddress = value.Serialize();

            byte[] socketAddressBytes = new byte[28];

            for (int i = 0; i < socketAddress.Size; i++)
            {
                socketAddressBytes[i] = socketAddress[i];
            }

            WriteBytes(socketAddressBytes);
        }
        public static void Serialize_Create_ReturnsEqual(IPAddress address, int expectedSize)
        {
            var           endPoint          = new IPEndPoint(address, 500);
            SocketAddress serializedAddress = endPoint.Serialize();

            Assert.Equal(address.AddressFamily, serializedAddress.Family);
            Assert.Equal(expectedSize, serializedAddress.Size);

            IPEndPoint createdEndPoint = Assert.IsType <IPEndPoint>(endPoint.Create(serializedAddress));

            Assert.NotSame(endPoint, createdEndPoint);
            Assert.Equal(endPoint, createdEndPoint);
        }
        /// <summary>
        /// Creates an unmanaged sockaddr structure to pass to a WinAPI function.
        /// </summary>
        /// <param name="ipEndPoint">IP address and port number</param>
        /// <returns>a handle for the structure. Use the AddrOfPinnedObject Method to get a stable pointer to the object. </returns>
        /// <remarks>When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. </remarks>
        public static GCHandle CreateSockaddrStructure(IPEndPoint ipEndPoint)
        {
            SocketAddress socketAddress = ipEndPoint.Serialize();

            // use an array of bytes instead of the sockaddr structure
            byte[]   sockAddrStructureBytes = new byte[socketAddress.Size];
            GCHandle sockAddrHandle         = GCHandle.Alloc(sockAddrStructureBytes, GCHandleType.Pinned);

            for (int i = 0; i < socketAddress.Size; ++i)
            {
                sockAddrStructureBytes[i] = socketAddress[i];
            }
            return(sockAddrHandle);
        }
Example #22
0
            /// <summary>
            /// This routine converts an IPEndPoint into a byte array that represents the
            /// underlying sockaddr structure of the correct type. Currently this routine
            /// supports only IPv4 and IPv6 socket address structures.
            /// </summary>
            /// <param name="endPoint">IPEndPoint to convert to a binary form</param>
            /// <returns>Binary array of the serialized socket address structure</returns>
            static public byte[] GetSockaddrBytes(IPEndPoint endPoint)
            {
                SocketAddress socketAddress = endPoint.Serialize();

                byte[] sockaddrBytes;

                sockaddrBytes = new byte[socketAddress.Size];

                for (int i = 0; i < socketAddress.Size; i++)
                {
                    sockaddrBytes[i] = socketAddress[i];
                }
                return(sockaddrBytes);
            }
Example #23
0
        int GetBestInterface(IPAddress destination)
        {
            var ep    = new IPEndPoint(destination, 0);
            var sa    = ep.Serialize();
            var arrSa = CopyArray(sa);
            int ifIndex;
            var ret = NativeMethods.GetBestInterfaceEx(arrSa, out ifIndex);

            if (ret != 0)
            {
                throw new Win32Exception();
            }
            return(ifIndex);
        }
        public static byte[] GetBytes(this IPEndPoint ipEndPoint)
        {
            var socketAddress =
                ipEndPoint.Serialize();

            var buffer =
                new byte[socketAddress.Size];

            for (var i = 0; i < socketAddress.Size; i++)
            {
                buffer[i] = socketAddress[i];
            }

            return(buffer);
        }
        public void CreateAndSerialize()
        {
            SocketAddress addr      = endPoint1.Serialize();
            EndPoint      endPoint3 = endPoint2.Create(addr);

            Assert.IsTrue(endPoint1.Equals(endPoint3), "#1");

            IPAddress  ipAddress = IPAddress.Parse("255.255.255.255");
            IPEndPoint endPoint4 = new IPEndPoint(ipAddress, MyMaxPort);

            addr = endPoint4.Serialize();
            EndPoint endPoint5 = endPoint2.Create(addr);

            Assert.IsTrue(endPoint4.Equals(endPoint5), "#2");
            Assert.AreEqual(endPoint5.ToString(), "255.255.255.255:" + MyMaxPort, "#3");
        }
Example #26
0
        void Socket_Address()
        {
            //Creates an IpEndPoint.
            IPAddress  ipAddress       = Dns.Resolve("http://localhost:50973/").AddressList[0];
            IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 11000);

            //Serializes the IPEndPoint.
            SocketAddress socketAddress = ipLocalEndPoint.Serialize();

            //Verifies that ipLocalEndPoint is now serialized by printing its contents.
            Console.WriteLine("Contents of the socketAddress are: " + socketAddress.ToString());
            //Checks the Family property.
            Console.WriteLine("The address family of the socketAddress is: " + socketAddress.Family.ToString());
            //Checks the underlying buffer size.
            Console.WriteLine("The size of the underlying buffer is: " + socketAddress.Size.ToString());
        }
Example #27
0
        private static SOCKADDR_STORAGE CreateSockAddrStorageStructure(int port)
        {
            var result = new SOCKADDR_STORAGE();

            result.ss_family = (short)AddressFamily.InterNetwork;
            var ipEndPoint    = new IPEndPoint(IPAddress.Any, port);
            var socketAddress = ipEndPoint.Serialize();

            result.__ss_pad1 = new byte[6];
            for (var i = 0; i < result.__ss_pad1.Length; i++)
            {
                result.__ss_pad1[i] = socketAddress[i + 2];
            }

            return(result);
        }
Example #28
0
        //"Connect to" constructor
        internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id, byte connectNum, NetDataWriter connectData)
            : this(netManager, remoteEndPoint, id)
        {
            _connectTime     = DateTime.UtcNow.Ticks;
            _connectionState = ConnectionState.Outgoing;
            ConnectionNum    = connectNum;

            //Make initial packet
            _connectRequestPacket = NetConnectRequestPacket.Make(connectData, remoteEndPoint.Serialize(), _connectTime);
            _connectRequestPacket.ConnectionNumber = connectNum;

            //Send request
            NetManager.SendRaw(_connectRequestPacket, EndPoint);

            NetDebug.Write(NetLogLevel.Trace, "[CC] ConnectId: {0}, ConnectNum: {1}", _connectTime, connectNum);
        }
        // The serializeEndpoint method serializes the endpoint and returns the
        // SocketAddress containing the serialized endpoint data.
        private static SocketAddress serializeEndpoint(IPEndPoint endpoint)
        {
            // Serialize IPEndPoint details to a SocketAddress instance.
            SocketAddress socketAddress = endpoint.Serialize();

            // Display the serialized endpoint information.
            Console.WriteLine("Endpoint.Serialize() : " + socketAddress.ToString());

            Console.WriteLine("Socket.Family : " + socketAddress.Family);
            Console.WriteLine("Socket.Size : " + socketAddress.Size);

            Console.WriteLine("Press any key to continue.");
            Console.ReadLine();

            return(socketAddress);
        }
Example #30
0
        public static void Main()
        {
            IPAddress  test1 = IPAddress.Parse("192.168.1.1");
            IPEndPoint ie    = new IPEndPoint(test1, 8000);

            Console.WriteLine("The IPEndPoint is: {0}", ie.ToString());
            Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily);
            Console.WriteLine("The address is: {0}, and the port is: {1}\n", ie.Address, ie.Port);
            Console.WriteLine("The min port number is: {0}", IPEndPoint.MinPort);
            Console.WriteLine("The max port number is: {0}\n", IPEndPoint.MaxPort);
            ie.Port = 80;
            Console.WriteLine("The changed IPEndPoint value is: {0}", ie.ToString());
            SocketAddress sa = ie.Serialize();

            Console.WriteLine("The SocketAddress is: {0}", sa.ToString());
        }
Example #31
0
        public static void SerializeCreate_Compare_Equal()
        { 
            //Serializing an IPEndPoint from a SocketAddress should produce the same output as creating one from a SocketAddress
            IPEndPoint ep = new IPEndPoint(testIpV41, 500);
            SocketAddress sa = ep.Serialize();
            
            EndPoint ep2 = ep.Create(sa);

            Assert.Equal(ep, ep2); 
        }