Ejemplo n.º 1
0
        public static void Create_Set_Invalid()
        {
            IPEndPoint ep = new IPEndPoint(testIpV41, 500);

            AssertExtensions.Throws <ArgumentException>("socketAddress", () => ep.Create(new SocketAddress(Sockets.AddressFamily.InterNetworkV6)));  //Different address families
            AssertExtensions.Throws <ArgumentException>("socketAddress", () => ep.Create(new SocketAddress(Sockets.AddressFamily.InterNetwork, 7))); //
        }
        // helper function to create an ACTUAL new IPEndPoint from this.
        // server needs it to store new connections as unique IPEndPoints.
        public IPEndPoint DeepCopyIPEndPoint()
        {
            // we need to create a new IPEndPoint from 'temp' SocketAddress.
            // there is no 'new IPEndPoint(SocketAddress) constructor.
            // so we need to be a bit creative...

            // allocate a placeholder IPAddress to copy
            // our SocketAddress into.
            // -> needs to be the same address family.
            IPAddress ipAddress;

            if (temp.Family == AddressFamily.InterNetworkV6)
            {
                ipAddress = IPAddress.IPv6Any;
            }
            else if (temp.Family == AddressFamily.InterNetwork)
            {
                ipAddress = IPAddress.Any;
            }
            else
            {
                throw new Exception($"Unexpected SocketAddress family: {temp.Family}");
            }

            // allocate a placeholder IPEndPoint
            // with the needed size form IPAddress.
            // (the real class. not NonAlloc)
            IPEndPoint placeholder = new IPEndPoint(ipAddress, 0);

            // the real IPEndPoint's .Create function can create a new IPEndPoint
            // copy from a SocketAddress.
            return((IPEndPoint)placeholder.Create(temp));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Reads the unmanaged sockaddr structure returned by a WinAPI function
        /// </summary>
        /// <param name="pSockaddrStructure">pointer to the unmanaged sockaddr structure</param>
        /// <returns>IP address and port number</returns>
        private static IPEndPoint ReadSockAddrStorageStructure(SOCKADDR_STORAGE sockAddrStorageStructure)
        {
            short         sAddressFamily = sockAddrStorageStructure.ss_family;
            AddressFamily addressFamily  = (AddressFamily)sAddressFamily;

            int        sockAddrSructureSize;
            IPEndPoint ipEndPointAny;

            switch (addressFamily)
            {
            case AddressFamily.InterNetwork:
                // IP v4 address
                sockAddrSructureSize = 8;
                var socketAddress = new SocketAddress(AddressFamily.InterNetwork, sockAddrSructureSize);
                socketAddress[0] = 2;
                socketAddress[1] = 0;
                for (int i = 2; i < sockAddrSructureSize; i++)
                {
                    socketAddress[i] = sockAddrStorageStructure.__ss_pad1[i - 2];
                }

                ipEndPointAny = new IPEndPoint(IPAddress.Any, 0);
                return((IPEndPoint)ipEndPointAny.Create(socketAddress));

            default:
                throw new ArgumentOutOfRangeException(nameof(sockAddrStorageStructure), "Unknown address family");
            }
        }
Ejemplo n.º 4
0
        static internal bool CheckEndPoint(SocketAddress sa)
        {
            if (!System.Environment.SocketSecurityEnabled)
            {
                return(true);
            }
            try
            {
                //weird, why is EndPoint.Create not static?  Making a temp instance to be able to call the function
                var temp     = new IPEndPoint(IPAddress.Loopback, 123);
                var endpoint = (IPEndPoint)temp.Create(sa);

                if (check_socket_policy == null)
                {
                    check_socket_policy = GetUnityCrossDomainHelperMethod("CheckSocketEndPoint");
                }
                return((bool)check_socket_policy.Invoke(null, new object [2] {
                    endpoint.Address.ToString(), endpoint.Port
                }));
            } catch (Exception e)
            {
                Console.WriteLine("Unexpected error while trying to CheckEndPoint() : " + e);
                return(false);
            }
        }
Ejemplo n.º 5
0
        public static void Create_InvalidSize_ThrowsArgumentException(IPAddress address, int size)
        {
            var endPoint      = new IPEndPoint(address, 500);
            var socketAddress = new SocketAddress(Sockets.AddressFamily.InterNetwork, size);

            AssertExtensions.Throws <ArgumentException>("socketAddress", () => endPoint.Create(socketAddress));
        }
Ejemplo n.º 6
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));
        }
        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");
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
0
        internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(null);
            }

            SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize);
            SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize);

            byte *        pMemoryBlob = (byte *)memoryBlob;
            HTTP_REQUEST *request     = (HTTP_REQUEST *)pMemoryBlob;
            IntPtr        address     = request->Address.pLocalAddress != null ? (IntPtr)(pMemoryBlob - (byte *)originalAddress + (byte *)request->Address.pLocalAddress) : IntPtr.Zero;

            CopyOutAddress(address, ref v4address, ref v6address);

            IPEndPoint endpoint = null;

            if (v4address != null)
            {
                endpoint = s_any.Create(v4address) as IPEndPoint;
            }
            else if (v6address != null)
            {
                endpoint = s_ipv6Any.Create(v6address) as IPEndPoint;
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(null);
            }
            return(endpoint);
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        public static void Create_DefaultAddress_Success(IPAddress address, int size, IPAddress expectedAddress)
        {
            var endPoint      = new IPEndPoint(address, 500);
            var socketAddress = new SocketAddress(address.AddressFamily, size);

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

            Assert.NotSame(endPoint, createdEndPoint);
            Assert.Equal(expectedAddress, createdEndPoint.Address);
            Assert.Equal(expectedAddress.AddressFamily, createdEndPoint.AddressFamily);
            Assert.Equal(0, createdEndPoint.Port);
        }
Ejemplo n.º 13
0
        internal static IPEndPoint /*!*/ UnpackSockAddr(MutableString /*!*/ stringAddress)
        {
            byte[]        bytes = stringAddress.ConvertToBytes();
            SocketAddress addr  = new SocketAddress(AddressFamily.InterNetwork, bytes.Length);

            for (int i = 0; i < bytes.Length; ++i)
            {
                addr[i] = bytes[i];
            }
            IPEndPoint ep = new IPEndPoint(0, 0);

            return((IPEndPoint)ep.Create(addr));
        }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        public void Ctor_IPAddressInt()
        {
            Assert.Throws <ArgumentNullException> (delegate {
                new IPEndPoint(null, 80);
            }, "IPEndPoint(null,int)");

            IPAddress a = new IPAddress(new byte [16]);

            Assert.AreEqual(AddressFamily.InterNetworkV6, a.AddressFamily, "IPAddress.AddressFamily");
            IPEndPoint ep = new IPEndPoint(a, 0);

            Assert.IsTrue(Object.ReferenceEquals(a, ep.Address), "Address");
            Assert.AreEqual(AddressFamily.InterNetworkV6, ep.AddressFamily, "AddressFamily");
            Assert.AreEqual(0, ep.Port, "Port");

            Assert.Throws <ArgumentException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.InterNetwork);
                ep.Create(sa);
            }, "Create(InterNetwork)");
            Assert.Throws <ArgumentException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.Unknown);
                ep.Create(sa);
            }, "Create(Unknown)");
            Assert.Throws <ArgumentException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.Unspecified);
                ep.Create(sa);
            }, "Create(Unspecified)");
            EndPoint ep2 = ep.Create(new SocketAddress(AddressFamily.InterNetworkV6));

            Assert.IsFalse(ep.Equals(null), "Equals(null)");
            Assert.IsTrue(ep.Equals(ep), "Equals(self)");
            Assert.IsTrue(ep.Equals(ep2), "Equals(Create)");

            Assert.AreEqual("InterNetworkV6:28:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize().ToString(), "Serialize");
//			Assert.AreEqual ("0000:0000:0000:0000:0000:0000:0.0.0.0:0", ep.ToString (), "ToString");
        }
Ejemplo n.º 16
0
        public MFTestResults SocketExceptionTest11_AccessDenied()
        {
            /// <summary>
            /// 1. Causes a AccessDenied error
            /// </summary>
            ///
            bool       isCorrectCatch = false;
            bool       isAnyCatch     = false;
            SocketPair testSockets    = new SocketPair(ProtocolType.Udp, SocketType.Dgram);

            try
            {
                try
                {
                    int clientPort = SocketTools.nextPort;
                    int serverPort = SocketTools.nextPort;
                    int tempPort   = serverPort;
                    testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
                    testSockets.Startup(clientPort, serverPort);
                    IPEndPoint epBroadcast    = new IPEndPoint(SocketTools.DottedDecimalToIp((byte)255, (byte)255, (byte)255, (byte)255), tempPort);
                    EndPoint   serverEndPoint = epBroadcast.Create(epBroadcast.Serialize());
                    testSockets.socketClient.SendTo(testSockets.bufSend, serverEndPoint);
                }
                catch (SocketException)
                {
                    isCorrectCatch = true;
                    isAnyCatch     = true;
                }
            }
            catch (System.Exception e)
            {
                isAnyCatch = true;
                Log.Comment("Incorrect exception caught: " + e.Message);
            }
            finally
            {
                testSockets.TearDown();
            }
            if (!isAnyCatch)
            {
                Log.Comment("No exception caught");
            }

            return(isCorrectCatch ? MFTestResults.Pass : MFTestResults.Fail);
        }
Ejemplo n.º 17
0
        public void SocketExceptionTest11_AccessDenied()
        {
            SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram);

            Assert.Throws(typeof(SocketException), () =>
            {
                int clientPort = SocketTools.nextPort;
                int serverPort = SocketTools.nextPort;
                int tempPort   = serverPort;
                testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
                testSockets.Startup(clientPort, serverPort);
                IPEndPoint epBroadcast  = new IPEndPoint(SocketTools.DottedDecimalToIp((byte)255, (byte)255, (byte)255, (byte)255), tempPort);
                EndPoint serverEndPoint = epBroadcast.Create(epBroadcast.Serialize());
                testSockets.socketClient.SendTo(testSockets.bufSend, serverEndPoint);
            });

            testSockets.TearDown();
        }
        /// <summary>
        /// Reads the unmanaged sockaddr structure returned by a WinAPI function
        /// </summary>
        /// <param name="pSockaddrStructure">pointer to the unmanaged sockaddr structure</param>
        /// <returns>IP address and port number</returns>
        public static IPEndPoint ReadSockaddrStructure(IntPtr pSockaddrStructure)
        {
            short         sAddressFamily = Marshal.ReadInt16(pSockaddrStructure);
            AddressFamily addressFamily  = (AddressFamily)sAddressFamily;

            int        sockAddrSructureSize;
            IPEndPoint ipEndPointAny;

            switch (addressFamily)
            {
            case AddressFamily.InterNetwork:
                // IP v4 address
                sockAddrSructureSize = 16;
                ipEndPointAny        = new IPEndPoint(IPAddress.Any, 0);
                break;

            case AddressFamily.InterNetworkV6:
                // IP v6 address
                sockAddrSructureSize = 28;
                ipEndPointAny        = new IPEndPoint(IPAddress.IPv6Any, 0);
                break;

            default:
                throw new ArgumentOutOfRangeException("pSockaddrStructure", "Unknown address family");
            }


            // get bytes of the sockadrr structure
            byte[] sockAddrSructureBytes = new byte[sockAddrSructureSize];
            Marshal.Copy(pSockaddrStructure, sockAddrSructureBytes, 0, sockAddrSructureSize);

            // create SocketAddress from bytes
            var socketAddress = new SocketAddress(AddressFamily.Unspecified, sockAddrSructureSize);

            for (int i = 0; i < sockAddrSructureSize; i++)
            {
                socketAddress[i] = sockAddrSructureBytes[i];
            }

            // create IPEndPoint from SocketAddress
            IPEndPoint result = (IPEndPoint)ipEndPointAny.Create(socketAddress);

            return(result);
        }
Ejemplo n.º 19
0
        /*
         * /// <summary>
         * /// Manually updates PlayerData from memory-mapped file.
         * /// </summary>
         * public void Update()
         * {
         *  Stopwatch sw = new Stopwatch();
         *  decimal avg = 0;
         *  for (int i = 0; i < 10000; i++)
         *  {
         *      sw.Start();
         *      // Make sure the memory-mapped file is loaded
         *      if (_mappedFile == null) OpenMumbleLink();
         *
         *      // Read memory-mapped file
         *      _accessor.Read(0, out data);
         *
         *      unsafe
         *      {
         *          fixed (LinkedMem* _data = &data)
         *          {
         *
         *              byte[] tempBytes = new byte[512];
         *              IntPtr tempByteIntPtr = new IntPtr((void*)_data->context);
         *              Marshal.Copy(tempByteIntPtr, tempBytes, 0, 512);
         *
         *
         *
         *              float f = _data->fAvatarPosition[0];
         *
         *
         *              int size = Marshal.SizeOf(typeof(LinkedMem));
         *              byte[] dataBytes = new byte[size];
         *              IntPtr dataBytesIntPtr = new IntPtr((void*)_data);
         *              Marshal.Copy(dataBytesIntPtr, dataBytes, 0, size);
         *              PlayerData pd = dataBytes.ToStruct<PlayerData>();
         *          }
         *      }
         *      sw.Stop();
         *      avg += sw.ElapsedTicks;
         *      sw.Reset();
         *  }
         *  avg /= 10000;
         *  Populate();
         * }
         *
         * /// <summary>
         * /// Manually updates PlayerData from byte array.
         * /// </summary>
         * /// <param name="byteArray">Data from which to populate the Player object.</param>
         * public void Update(byte[] byteArray)
         * {
         *  if (Marshal.SizeOf(typeof(PlayerData)) != byteArray.Length)
         *  {
         *      throw new ArgumentException(String.Format(
         *          "The parameter {0} (length {1}) is invalid for converting to PlayerData struct.",
         *          (MethodBase.GetCurrentMethod().GetParameters()[0]).Name,
         *          byteArray.Length));
         *  }
         *  _pd = byteArray.ToStruct<PlayerData>();
         *  Populate();
         * }
         *
         * /// <summary>
         * /// Poll the memory-mapped file for data.
         * /// </summary>
         * private void Populate()
         * {
         *  PopulateIdentity();
         *  PopulateServerAddress();
         * }
         *
         * /// <summary>
         * /// Parses identity string into Identity struct using JsonConvert.
         * /// </summary>
         * private void PopulateIdentity()
         * {
         *  string identityJson = _pd.identityString.Substring(0, _pd.identityString.IndexOf('}') + 1);
         *  if (identityJson.Length > 0)
         *  {
         *      _pi = JsonConvert.DeserializeObject<Identity>(identityJson);
         *  }
         * }
         *
         * /// <summary>
         * /// Parses server address byte array into IPEndPoint.
         * /// </summary>
         * private void PopulateServerAddress()
         * {
         *  _serverAddress = GetServerAddress(_pd.serverAddress);
         * }
         */

        /// <summary>
        /// Helper method to convert byte array into IPEndpoint.
        /// </summary>
        /// <param name="serverAddressBytes"></param>
        /// <returns></returns>
        public static IPEndPoint GetServerAddress(byte[] serverAddressBytes)
        {
            if (serverAddressBytes.Length < 2)
            {
                return(new IPEndPoint(IPAddress.Any, 0));
            }
            AddressFamily addressFamily = (AddressFamily)BitConverter.ToInt16(serverAddressBytes, 0);
            int           sockAddrSructureSize;
            IPEndPoint    ipEndPointAny;
            IPEndPoint    result;

            switch (addressFamily)
            {
            case AddressFamily.InterNetwork:
                // IP v4 address
                sockAddrSructureSize = 16;
                ipEndPointAny        = new IPEndPoint(IPAddress.Any, 0);
                break;

            case AddressFamily.InterNetworkV6:
                // IP v6 address
                sockAddrSructureSize = 28;
                ipEndPointAny        = new IPEndPoint(IPAddress.IPv6Any, 0);
                break;

            default:
                return(new IPEndPoint(IPAddress.Any, 0));
                //throw new ArgumentOutOfRangeException("pSockaddrStructure", "Unknown address family");
            }

            var socketAddress = new SocketAddress(AddressFamily.Unspecified, sockAddrSructureSize);

            for (int i = 0; i < sockAddrSructureSize; i++)
            {
                socketAddress[i] = serverAddressBytes[i];
            }
            result = (IPEndPoint)ipEndPointAny.Create(socketAddress);
            return(result);
        }
Ejemplo n.º 20
0
        public void Address()
        {
            IPEndPoint ep = new IPEndPoint(0, 0);

            Assert.AreEqual(AddressFamily.InterNetwork, ep.AddressFamily, "AddressFamily");
            ep.Address = null;
            Assert.IsNull(ep.Address, "null");

            Assert.Throws <NullReferenceException> (delegate {
                Assert.AreEqual(AddressFamily.InterNetwork, ep.AddressFamily);
            }, "null-AddressFamily");
            Assert.Throws <NullReferenceException> (delegate {
                ep.ToString();
            }, "null-ToString");
            Assert.Throws <NullReferenceException> (delegate {
                ep.Create(new SocketAddress(AddressFamily.InterNetworkV6));
            }, "null-Create");

            // change family
            IPAddress a = new IPAddress(new byte [16]);

            ep.Address = a;
            Assert.AreEqual(AddressFamily.InterNetworkV6, ep.AddressFamily, "v6-AddressFamily");
        }
Ejemplo n.º 21
0
        private static IPEndPoint CreateManagedSocketAddress(IntPtr socketAddressPtr)
        {
            var addressFamily = (AddressFamily)Marshal.ReadInt16(socketAddressPtr);

            int        socketAddressSize;
            IPEndPoint ipEndPointAny;

            switch (addressFamily)
            {
            case AddressFamily.InterNetwork:
                socketAddressSize = 16;
                ipEndPointAny     = new IPEndPoint(IPAddress.Any, 0);
                break;

            case AddressFamily.InterNetworkV6:
                socketAddressSize = 28;
                ipEndPointAny     = new IPEndPoint(IPAddress.IPv6Any, 0);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var socketAddressBytes = new byte[socketAddressSize];

            Marshal.Copy(socketAddressPtr, socketAddressBytes, 0, socketAddressSize);

            var socketAddress = new SocketAddress(AddressFamily.Unspecified, socketAddressSize);

            for (var i = 0; i < socketAddressSize; ++i)
            {
                socketAddress[i] = socketAddressBytes[i];
            }

            return((IPEndPoint)ipEndPointAny.Create(socketAddress));
        }
        static private IPEndPoint QueryRoutingInterface(
            Socket socket,
            IPEndPoint remoteEndPoint)
        {
            var socketAddress = remoteEndPoint.Serialize();

            var remoteAddressBytes = new byte[socketAddress.Size];

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

            var outBytes = new byte[remoteAddressBytes.Length];

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

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

            return((IPEndPoint)remoteEndPoint.Create(socketAddress));
        }
Ejemplo n.º 23
0
        public void Ctor_LongInt()
        {
            IPEndPoint ep = new IPEndPoint(0, 80);

            Assert.AreEqual(new IPAddress(0), ep.Address, "Address");
            Assert.AreEqual(AddressFamily.InterNetwork, ep.AddressFamily, "AddressFamily");
            Assert.AreEqual(80, ep.Port, "Port");

            Assert.Throws <ArgumentNullException> (delegate {
                ep.Create(null);
            }, "Create(null)");

            // note: documented as ArgumentException
            Assert.Throws <ArgumentOutOfRangeException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.InterNetwork, 1);
                Assert.IsTrue(sa.Size < 8, "Size");
                ep.Create(sa);
            }, "Create(bad-size)");

            Assert.Throws <ArgumentException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.InterNetworkV6);
                Assert.IsTrue(sa.Size >= 8, "SizeV6");
                ep.Create(sa);
            }, "Create(InterNetworkV6)");
            Assert.Throws <ArgumentException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.Unknown);
                ep.Create(sa);
            }, "Create(Unknown)");
            Assert.Throws <ArgumentException> (delegate {
                SocketAddress sa = new SocketAddress(AddressFamily.Unspecified);
                ep.Create(sa);
            }, "Create(Unspecified)");
            EndPoint ep2 = ep.Create(new SocketAddress(AddressFamily.InterNetwork));

            Assert.IsFalse(ep.Equals(null), "Equals(null)");
            Assert.IsTrue(ep.Equals(ep), "Equals(self)");
            Assert.IsFalse(ep.Equals(ep2), "Equals(Create)");

            Assert.AreEqual("InterNetwork:16:{0,80,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize().ToString(), "Serialize");
            Assert.AreEqual("0.0.0.0:80", ep.ToString(), "ToString");
        }
Ejemplo n.º 24
0
        public static void Create_NullSocketAddress_ThrowsArgumentNullException()
        {
            var endPoint = new IPEndPoint(1, 500);

            Assert.Throws <ArgumentNullException>("socketAddress", () => endPoint.Create(null));
        }
Ejemplo n.º 25
0
 public static void Create_InvalidAddressFamily_ThrowsArgumentException(IPEndPoint endPoint, SocketAddress socketAddress)
 {
     AssertExtensions.Throws <ArgumentException>("socketAddress", () => endPoint.Create(socketAddress));
 }
Ejemplo n.º 26
0
 public static void Create_Set_Invalid()
 {
     IPEndPoint ep = new IPEndPoint(testIpV41, 500);
     Assert.Throws<ArgumentException>(() => ep.Create(new SocketAddress(Sockets.AddressFamily.InterNetworkV6))); //Different address families
     Assert.Throws<ArgumentException>(() => ep.Create(new SocketAddress(Sockets.AddressFamily.InterNetwork, 7))); //
 }
Ejemplo n.º 27
0
        private void RecvUdpDataLooper(object obj)
        {
            try
            {
                uint          startConvId = 10000;
                const int     pollTimeout = 100000;
                List <Packet> packets     = new List <Packet>();
                byte[]        rawBuffer   = new byte[KcpConstants.Packet_Length];
                EndPoint      remote      = new IPEndPoint(IPAddress.Any, 0);

                while (!m_Dispose)
                {
                    if (!m_Socket.Poll(pollTimeout, SelectMode.SelectRead))
                    {
                        continue;
                    }

                    if (m_Dispose)
                    {
                        break;
                    }

                    int size = m_Socket.ReceiveFrom(rawBuffer, SocketFlags.None, ref remote);
                    if (size > 0)
                    {
                        uint cid = (uint)remote.GetHashCode();
                        if (!m_Channels.TryGetValue(cid, out ServerChannel channel))
                        {
                            if (size == 4)
                            {
                                uint flag = KcpHelper.Decode32u(rawBuffer, 0);
                                if (flag == KcpConstants.Flag_Connect)
                                {
                                    uint     conv  = startConvId++;
                                    EndPoint point = remote.Create(remote.Serialize());
                                    channel = new ServerChannel(new KcpConServer(cid, conv, m_Socket, point));

                                    if (m_Channels.TryAdd(cid, channel))
                                    {
                                        KcpHelper.Encode32u(rawBuffer, 0, KcpConstants.Flag_Connect);
                                        KcpHelper.Encode32u(rawBuffer, 4, conv);
                                        channel.Send(rawBuffer, 0, 8);
                                        channel.Flush();
                                    }
                                }
                            }
                            else
                            {
                                Logger.Error($"not connect size={size}");
                            }
                        }
                        else if (size > KcpConstants.Head_Size)
                        {
                            uint remoteCid = KcpHelper.Decode32u(rawBuffer, 0);
                            if (cid == remoteCid)
                            {
                                byte msgChannel = rawBuffer[KcpConstants.Conv_Size];
                                if (msgChannel == MsgChannel.Reliable)
                                {
                                    channel.Input(rawBuffer, KcpConstants.Head_Size, size - KcpConstants.Head_Size);
                                    channel.RecvReliablePackets(m_Process, packets, m_Listener);
                                }
                                else if (msgChannel == MsgChannel.Unreliable)
                                {
                                    channel.RecvUnreliablePackets(rawBuffer, KcpConstants.Head_Size, size - KcpConstants.Head_Size, m_Process, packets);
                                }
                            }
                            else
                            {
                                Logger.Error($"conv {cid} != {remoteCid}");
                            }
                        }
                        else
                        {
                            Logger.Error($"size={size} < {KcpConstants.Head_Size}");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.ToString());
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Called when [new client accepted].
        /// </summary>
        /// <param name="listener">The listener.</param>
        /// <param name="client">The client.</param>
        /// <param name="state">The state.</param>
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            var paramArray = state as object[];

            var receivedData = paramArray[0] as byte[];
            var socketAddress = paramArray[1] as SocketAddress;
            var remoteEndPoint = (socketAddress.Family == AddressFamily.InterNetworkV6 ? m_EndPointIPv6.Create(socketAddress) : m_EndPointIPv4.Create(socketAddress)) as IPEndPoint;

            if (m_IsUdpRequestInfo)
            {
                ProcessPackageWithSessionID(client, remoteEndPoint, receivedData);
            }
            else
            {
                ProcessPackageWithoutSessionID(client, remoteEndPoint, receivedData);
            }
        }
Ejemplo n.º 29
0
 public override EndPoint Create(SocketAddress socketAddress)
 {
     mIsDirty = true;
     return(mIPEndPoint.Create(socketAddress));
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Called when [new client accepted].
        /// </summary>
        /// <param name="listener">The listener.</param>
        /// <param name="client">The client.</param>
        /// <param name="state">The state.</param>
        protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
        {
            var paramArray = state as object[];

            var receivedData   = paramArray[0] as byte[];
            var socketAddress  = paramArray[1] as SocketAddress;
            var remoteEndPoint = (socketAddress.Family == AddressFamily.InterNetworkV6 ? m_EndPointIPv6.Create(socketAddress) : m_EndPointIPv4.Create(socketAddress)) as IPEndPoint;

            try
            {
                if (m_IsUdpRequestInfo)
                {
                    ProcessPackageWithSessionID(client, remoteEndPoint, receivedData);
                }
                else
                {
                    ProcessPackageWithoutSessionID(client, remoteEndPoint, receivedData);
                }
            }
            catch (Exception e)
            {
                if (AppServer.Logger.IsErrorEnabled)
                {
                    AppServer.Logger.Error("Process UDP package error!", e);
                }
            }
        }
Ejemplo n.º 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); 
        }
Ejemplo n.º 32
0
        private void UdpReceiveEndHandler(IAsyncResult ar)
        {
            Circuit circuit;
            var     pck = (UDPReceivePacket)ar.AsyncState;

            try
            {
                pck.DataLength = m_UdpSocket.EndReceiveFrom(ar, ref pck.RemoteEndPoint);
            }
            catch
            {
                return;
            }
            finally
            {
                if (m_InboundRunning)
                {
                    BeginUdpReceive();
                }
            }

            pck.TransferredAtTime = Environment.TickCount;
            pck.EnqueuedAtTime    = Environment.TickCount;

            /* we do not want to spend time on decoding packets that are unknown where they belong */
            if (!m_Circuits.TryGetValue(pck.RemoteEndPoint, out circuit) || circuit.ForceUseCircuitCode)
            {
                try
                {
                    /* check whether we got an UseCircuitCode */
                    var mType = pck.ReadMessageType();
                    if (MessageType.UseCircuitCode == mType)
                    {
                        var circuitcode = pck.ReadUInt32();
                        /* it is, so we have actually to look for the circuitcode and set up the remote endpoint here */
                        lock (m_UseCircuitCodeProcessingLock)
                        {
                            if (m_Circuits.TryGetValue(circuitcode, out circuit))
                            {
                                circuit.ForceUseCircuitCode = false;
                                var sessionID = pck.ReadUUID();
                                var agentID   = pck.ReadUUID();
                                var acircuit  = circuit as AgentCircuit;
                                if (acircuit != null)
                                {
                                    /* there it is check for SessionID and AgentID */
                                    if (!acircuit.SessionID.Equals(sessionID) ||
                                        !acircuit.AgentID.Equals(agentID) ||
                                        !VerifyEndpointAddress(acircuit, pck.RemoteEndPoint))
                                    {
                                        /* no match on SessionID or AgentID */
                                        m_Log.DebugFormat("Unmatched UseCircuitCode for AgentID {0} SessionID {1} CircuitCode {2} received", agentID, sessionID, circuitcode);
                                    }
                                    else
                                    {
                                        /* it matches, so we have to change the actual key */
                                        var endpoint = new IPEndPoint(0, 0);
                                        var ep       = endpoint.Create(pck.RemoteEndPoint.Serialize());
                                        m_Circuits.Remove(circuit.CircuitCode);
                                        m_Circuits.Add(ep, circuit.CircuitCode, circuit);
                                        circuit.RemoteEndPoint = ep;
                                        try
                                        {
                                            circuit.Start();

                                            var scene = Scene;
                                            RegionOptionFlags regionFlags = scene.RegionSettings.AsFlags;
                                            var rh = new RegionHandshake
                                            {
                                                RegionFlags          = regionFlags,
                                                SimAccess            = scene.Access,
                                                SimName              = scene.Name,
                                                SimOwner             = scene.Owner.ID,
                                                IsEstateManager      = scene.IsEstateManager(acircuit.Agent.Owner),
                                                WaterHeight          = scene.RegionSettings.WaterHeight,
                                                BillableFactor       = 1,
                                                TerrainStartHeight00 = scene.RegionSettings.Elevation1SW,
                                                TerrainStartHeight01 = scene.RegionSettings.Elevation2SW,
                                                TerrainStartHeight10 = scene.RegionSettings.Elevation1NW,
                                                TerrainStartHeight11 = scene.RegionSettings.Elevation2NW,
                                                TerrainHeightRange00 = scene.RegionSettings.Elevation1SE,
                                                TerrainHeightRange01 = scene.RegionSettings.Elevation2SE,
                                                TerrainHeightRange10 = scene.RegionSettings.Elevation1NE,
                                                TerrainHeightRange11 = scene.RegionSettings.Elevation2NE,
                                                TerrainBase0         = UUID.Zero,
                                                TerrainBase1         = UUID.Zero,
                                                TerrainBase2         = UUID.Zero,
                                                TerrainBase3         = UUID.Zero,
                                                TerrainDetail0       = scene.RegionSettings.TerrainTexture1,
                                                TerrainDetail1       = scene.RegionSettings.TerrainTexture2,
                                                TerrainDetail2       = scene.RegionSettings.TerrainTexture3,
                                                TerrainDetail3       = scene.RegionSettings.TerrainTexture4,
                                                RegionID             = scene.ID,
                                                CacheID              = UUID.Random,
                                                CPUClassID           = 9,
                                                CPURatio             = 1,
                                                ColoName             = string.Empty,
                                                ProductSKU           = VersionInfo.SimulatorVersion,
                                                ProductName          = scene.ProductName
                                            };
                                            rh.RegionExtData.Add(new RegionHandshake.RegionExtDataEntry
                                            {
                                                RegionFlagsExtended = (ulong)regionFlags,
                                                RegionProtocols     = RegionProtocolFlags.AgentAppearanceService
                                            });

                                            /* Immediate Ack */
                                            circuit.SendCircuitPacket(UDPPacket.PacketAckImmediate(pck.SequenceNumber));

                                            circuit.SendMessage(rh);
                                            return;
                                        }
                                        catch (Exception e)
                                        {
                                            m_Log.DebugFormat("UseCircuitCode Exception {0} {1}\n{2}", e.GetType().Name, e.Message, e.StackTrace);
                                            circuit.Stop();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                m_Log.DebugFormat("UseCircuitCode received for unknown circuit {0}", circuitcode);
                            }
                        }
                    }
                    else if (MessageType.NetTest == mType && (uint)m_NetTestSeqNumber == pck.SequenceNumber ||
                             pck.ReadUInt16() == (ushort)LocalPort)
                    {
                        OnNetTest?.Invoke(((IPEndPoint)pck.RemoteEndPoint).Address, LocalPort);
                        return;
                    }
#if DEBUG
                    if (mType != MessageType.StartPingCheck)
                    {
                        /* do not show that message for a StartPingCheck */
                        m_Log.DebugFormat("Unmatched endpoint address {0} for UDP server at port {1}", pck.RemoteEndPoint.ToString(), LocalPort);
                    }
#endif
                }
                catch
                {
                    /* no action required */
                }

                return;
            }

            /* here we spend time on decoding */
            if (pck.IsUndersized)
            {
                /* packet is undersized so we throw it away as well */
                return;
            }

            /* now we know that the packet is at least valid
             * We can pass it to the circuit handler.
             */

            /* we decode the ack numbers here, the code does not need to be implemented in the UDP Circuit Handler */
            List <UInt32> acknumbers = null;

            if (pck.HasAckFlag)
            {
                try
                {
                    acknumbers = pck.Acks;
                }
                catch
                {
                    /* packet is undersized so we throw it away as well */
                    return;
                }
            }

            try
            {
                circuit.PacketReceived(pck.RemoteEndPoint, pck, acknumbers);
            }
            catch (Exception e)
            {
                /* we catch all issues here */
                m_Log.ErrorFormat("Exception {0} => {1} at {2}", e.GetType().Name, e.ToString(), e.StackTrace);
            }
            /* return the buffer to the pool */
        }