Create() public method

public Create ( SocketAddress socketAddress ) : EndPoint
socketAddress SocketAddress
return EndPoint
		/// <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;
		}
示例#2
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");
		}
        public string sortIpAddressList(string IPAddressList)
        {

            //---------------------------------------------------------------            
            //If the input is nothing, return nothing
            //---------------------------------------------------------------
            if(IPAddressList == null || IPAddressList.Length == 0)
            {
                return string.Empty;
            }

            //---------------------------------------------------------------            
            //The input string is supposed to be a list of IPAddress strings 
            //separated by a semicolon
            //---------------------------------------------------------------
            string[] IPAddressStrings = IPAddressList.Split(new char[] {';'});
			if(IPAddressStrings.Length > MAX_IPADDRESS_LIST_LENGTH)
			{
				throw new ArgumentException(string.Format(
									SR.GetString(SR.net_max_ip_address_list_length_exceeded),
									MAX_IPADDRESS_LIST_LENGTH), "IPAddressList");
			}
			

            //----------------------------------------------------------------
            //If there are no separators, just return the original string
            //----------------------------------------------------------------
            if(IPAddressStrings.Length == 1)
            {
                return IPAddressList;
            }

            //----------------------------------------------------------------
            //Parse the strings into Socket Address buffers
            //----------------------------------------------------------------
            SocketAddress[] SockAddrIn6List = new SocketAddress[IPAddressStrings.Length];
            for(int i = 0; i < IPAddressStrings.Length; i++)
            {
            	//Trim leading and trailing spaces
                IPAddressStrings[i] = IPAddressStrings[i].Trim();
				if(IPAddressStrings[i].Length == 0)
	                throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
                SocketAddress saddrv6 = new SocketAddress(AddressFamily.InterNetworkV6, 
															SocketAddress.IPv6AddressSize);
            	//Parse the string to a v6 address structure
                SocketError errorCode =
                    UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
                        IPAddressStrings[i],
                        AddressFamily.InterNetworkV6,
                        IntPtr.Zero,
                        saddrv6.m_Buffer,
                        ref saddrv6.m_Size );
                if(errorCode != SocketError.Success)
                {
                    //Could not parse this into a SOCKADDR_IN6
                    //See if we can parse this into s SOCKEADDR_IN
                    SocketAddress saddrv4 = new SocketAddress(AddressFamily.InterNetwork, SocketAddress.IPv4AddressSize);
                    errorCode =
                        UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
                            IPAddressStrings[i],
                            AddressFamily.InterNetwork,
                            IntPtr.Zero,
                            saddrv4.m_Buffer,
                            ref saddrv4.m_Size );
                    if(errorCode != SocketError.Success)
                    {
                        //This address is neither IPv4 nor IPv6 string throw
		                throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
                    }
					else
					{
						//This is a valid IPv4 address. We need to map this to a mapped v6 address
						IPEndPoint dummy = new IPEndPoint(IPAddress.Any, 0);
						IPEndPoint IPv4EndPoint = (IPEndPoint)dummy.Create(saddrv4);
						byte[] IPv4AddressBytes = IPv4EndPoint.Address.GetAddressBytes();
						byte[] IPv6MappedAddressBytes = new byte[16]; //IPv6 is 16 bytes address
						for(int j = 0; j < 10; j++) IPv6MappedAddressBytes[j] = 0x00;
						IPv6MappedAddressBytes[10] = 0xFF;
						IPv6MappedAddressBytes[11] = 0xFF;						
						IPv6MappedAddressBytes[12] = IPv4AddressBytes[0];
						IPv6MappedAddressBytes[13] = IPv4AddressBytes[1];						
						IPv6MappedAddressBytes[14] = IPv4AddressBytes[2];
						IPv6MappedAddressBytes[15] = IPv4AddressBytes[3];
						IPAddress v6Address = new IPAddress(IPv6MappedAddressBytes);
						IPEndPoint IPv6EndPoint = new IPEndPoint(v6Address, IPv4EndPoint.Port);
						saddrv6 = IPv6EndPoint.Serialize();
					}
                }

				//At this point,we have SOCKADDR_IN6 buffer
				//add them to the list 
				SockAddrIn6List[i] = saddrv6;
            }

           	//----------------------------------------------------------------
            //All the IPAddress strings are parsed into 
            //either a native v6 address or mapped v6 address
            //The Next step is to prepare for calling the WSAIOctl
            //By creating a SOCKET_ADDRESS_LIST
            //----------------------------------------------------------------
            int cbRequiredBytes = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST)) + 
            						(SockAddrIn6List.Length -1)*Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS));
			Dictionary<IntPtr, KeyValuePair<SocketAddress, string> > UnmanagedToManagedMapping = new Dictionary<IntPtr, KeyValuePair<SocketAddress, string>>();
			GCHandle[] GCHandles = new GCHandle[SockAddrIn6List.Length];
			for(int i = 0; i < SockAddrIn6List.Length; i++)
			{
				GCHandles[i] = GCHandle.Alloc(SockAddrIn6List[i].m_Buffer, GCHandleType.Pinned);
			}
			IntPtr pSocketAddressList = Marshal.AllocHGlobal(cbRequiredBytes);
			try
			{
				//---------------------------------------------------
				//Create a socket address list structure
				//and set the pointers to the pinned sock addr buffers
				//---------------------------------------------------
				unsafe 
				{
					UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST* pList 
								= (UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST*)pSocketAddressList;
					pList->iAddressCount = SockAddrIn6List.Length; //Set the number of addresses
					UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS* pSocketAddresses =
							&pList->Addresses;
					for(int i = 0; i < pList->iAddressCount; i++)
					{
						pSocketAddresses[i].iSockaddrLength = SocketAddress.IPv6AddressSize;
						pSocketAddresses[i].lpSockAddr = GCHandles[i].AddrOfPinnedObject();
						UnmanagedToManagedMapping[pSocketAddresses[i].lpSockAddr]
							= new KeyValuePair<SocketAddress, string>(SockAddrIn6List[i], IPAddressStrings[i]);
					}
					//---------------------------------------------------
					//Create a socket and ask it to sort the list 
					//---------------------------------------------------								
					Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
 					int cbProcessed = s.IOControl(
							IOControlCode.AddressListSort,
							pSocketAddressList, //Input buffer
							cbRequiredBytes, //Buffer size
							pSocketAddressList, //Outbuffer - same as in buffer
							cbRequiredBytes //out buffer size - same as in buffer size
							);

					//---------------------------------------------------
					//At this point The sorting is complete
					//---------------------------------------------------
					StringBuilder sb = new StringBuilder();
					for(int i = 0; i < pList->iAddressCount; i++)
					{
						IntPtr lpSockAddr = pSocketAddresses[i].lpSockAddr;
						KeyValuePair<SocketAddress, string> kv = UnmanagedToManagedMapping[lpSockAddr];
						sb.Append(kv.Value);
						if(i != pList->iAddressCount - 1) sb.Append(";");
					}					
					return sb.ToString();
				}
			}
			finally
			{
				if(pSocketAddressList != IntPtr.Zero)
				{
					Marshal.FreeHGlobal(pSocketAddressList);
				}
				for(int i = 0; i < GCHandles.Length; i++)
				{
					if(GCHandles[i].IsAllocated)
						GCHandles[i].Free();
				}				
			}

        }
示例#4
0
        public string sortIpAddressList(string IPAddressList)
        {
            //---------------------------------------------------------------
            //If the input is nothing, return nothing
            //---------------------------------------------------------------
            if (IPAddressList == null || IPAddressList.Length == 0)
            {
                return(string.Empty);
            }

            //---------------------------------------------------------------
            //The input string is supposed to be a list of IPAddress strings
            //separated by a semicolon
            //---------------------------------------------------------------
            string[] IPAddressStrings = IPAddressList.Split(new char[] { ';' });
            if (IPAddressStrings.Length > MAX_IPADDRESS_LIST_LENGTH)
            {
                throw new ArgumentException(string.Format(
                                                SR.GetString(SR.net_max_ip_address_list_length_exceeded),
                                                MAX_IPADDRESS_LIST_LENGTH), "IPAddressList");
            }


            //----------------------------------------------------------------
            //If there are no separators, just return the original string
            //----------------------------------------------------------------
            if (IPAddressStrings.Length == 1)
            {
                return(IPAddressList);
            }

            //----------------------------------------------------------------
            //Parse the strings into Socket Address buffers
            //----------------------------------------------------------------
            SocketAddress[] SockAddrIn6List = new SocketAddress[IPAddressStrings.Length];
            for (int i = 0; i < IPAddressStrings.Length; i++)
            {
                //Trim leading and trailing spaces
                IPAddressStrings[i] = IPAddressStrings[i].Trim();
                if (IPAddressStrings[i].Length == 0)
                {
                    throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
                }
                SocketAddress saddrv6 = new SocketAddress(AddressFamily.InterNetworkV6,
                                                          SocketAddress.IPv6AddressSize);
                //Parse the string to a v6 address structure
                SocketError errorCode =
                    UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
                        IPAddressStrings[i],
                        AddressFamily.InterNetworkV6,
                        IntPtr.Zero,
                        saddrv6.m_Buffer,
                        ref saddrv6.m_Size);
                if (errorCode != SocketError.Success)
                {
                    //Could not parse this into a SOCKADDR_IN6
                    //See if we can parse this into s SOCKEADDR_IN
                    SocketAddress saddrv4 = new SocketAddress(AddressFamily.InterNetwork, SocketAddress.IPv4AddressSize);
                    errorCode =
                        UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
                            IPAddressStrings[i],
                            AddressFamily.InterNetwork,
                            IntPtr.Zero,
                            saddrv4.m_Buffer,
                            ref saddrv4.m_Size);
                    if (errorCode != SocketError.Success)
                    {
                        //This address is neither IPv4 nor IPv6 string throw
                        throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
                    }
                    else
                    {
                        //This is a valid IPv4 address. We need to map this to a mapped v6 address
                        IPEndPoint dummy                  = new IPEndPoint(IPAddress.Any, 0);
                        IPEndPoint IPv4EndPoint           = (IPEndPoint)dummy.Create(saddrv4);
                        byte[]     IPv4AddressBytes       = IPv4EndPoint.Address.GetAddressBytes();
                        byte[]     IPv6MappedAddressBytes = new byte[16];                     //IPv6 is 16 bytes address
                        for (int j = 0; j < 10; j++)
                        {
                            IPv6MappedAddressBytes[j] = 0x00;
                        }
                        IPv6MappedAddressBytes[10] = 0xFF;
                        IPv6MappedAddressBytes[11] = 0xFF;
                        IPv6MappedAddressBytes[12] = IPv4AddressBytes[0];
                        IPv6MappedAddressBytes[13] = IPv4AddressBytes[1];
                        IPv6MappedAddressBytes[14] = IPv4AddressBytes[2];
                        IPv6MappedAddressBytes[15] = IPv4AddressBytes[3];
                        IPAddress  v6Address    = new IPAddress(IPv6MappedAddressBytes);
                        IPEndPoint IPv6EndPoint = new IPEndPoint(v6Address, IPv4EndPoint.Port);
                        saddrv6 = IPv6EndPoint.Serialize();
                    }
                }

                //At this point,we have SOCKADDR_IN6 buffer
                //add them to the list
                SockAddrIn6List[i] = saddrv6;
            }

            //----------------------------------------------------------------
            //All the IPAddress strings are parsed into
            //either a native v6 address or mapped v6 address
            //The Next step is to prepare for calling the WSAIOctl
            //By creating a SOCKET_ADDRESS_LIST
            //----------------------------------------------------------------
            int cbRequiredBytes = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST)) +
                                  (SockAddrIn6List.Length - 1) * Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS));
            Dictionary <IntPtr, KeyValuePair <SocketAddress, string> > UnmanagedToManagedMapping = new Dictionary <IntPtr, KeyValuePair <SocketAddress, string> >();

            GCHandle[] GCHandles = new GCHandle[SockAddrIn6List.Length];
            for (int i = 0; i < SockAddrIn6List.Length; i++)
            {
                GCHandles[i] = GCHandle.Alloc(SockAddrIn6List[i].m_Buffer, GCHandleType.Pinned);
            }
            IntPtr pSocketAddressList = Marshal.AllocHGlobal(cbRequiredBytes);

            try
            {
                //---------------------------------------------------
                //Create a socket address list structure
                //and set the pointers to the pinned sock addr buffers
                //---------------------------------------------------
                unsafe
                {
                    UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST *pList
                        = (UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST *)pSocketAddressList;
                    pList->iAddressCount = SockAddrIn6List.Length;                     //Set the number of addresses
                    UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS *pSocketAddresses =
                        &pList->Addresses;
                    for (int i = 0; i < pList->iAddressCount; i++)
                    {
                        pSocketAddresses[i].iSockaddrLength = SocketAddress.IPv6AddressSize;
                        pSocketAddresses[i].lpSockAddr      = GCHandles[i].AddrOfPinnedObject();
                        UnmanagedToManagedMapping[pSocketAddresses[i].lpSockAddr]
                            = new KeyValuePair <SocketAddress, string>(SockAddrIn6List[i], IPAddressStrings[i]);
                    }
                    //---------------------------------------------------
                    //Create a socket and ask it to sort the list
                    //---------------------------------------------------
                    Socket s           = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    int    cbProcessed = s.IOControl(
                        IOControlCode.AddressListSort,
                        pSocketAddressList,                             //Input buffer
                        cbRequiredBytes,                                //Buffer size
                        pSocketAddressList,                             //Outbuffer - same as in buffer
                        cbRequiredBytes                                 //out buffer size - same as in buffer size
                        );

                    //---------------------------------------------------
                    //At this point The sorting is complete
                    //---------------------------------------------------
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < pList->iAddressCount; i++)
                    {
                        IntPtr lpSockAddr = pSocketAddresses[i].lpSockAddr;
                        KeyValuePair <SocketAddress, string> kv = UnmanagedToManagedMapping[lpSockAddr];
                        sb.Append(kv.Value);
                        if (i != pList->iAddressCount - 1)
                        {
                            sb.Append(";");
                        }
                    }
                    return(sb.ToString());
                }
            }
            finally
            {
                if (pSocketAddressList != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pSocketAddressList);
                }
                for (int i = 0; i < GCHandles.Length; i++)
                {
                    if (GCHandles[i].IsAllocated)
                    {
                        GCHandles[i].Free();
                    }
                }
            }
        }
示例#5
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);
 }
示例#6
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;
        }
示例#7
0
        public MFTestResults NetTest5_IPEndPointBasic()
        {
            /// <summary>
            /// 1. Creates 30 Random IPs between 0.0.0.0 and 255.255.255.127
            /// 2. Verifies that they can be constructed as IPEndPoints with both ctors
            /// 3. Verifies that their data, ToString and GetHashCode funcs return normally
            /// 4. Clones one with Create and verifies the above funcs again
            /// </summary>
            ///
            bool testResult = true;
            try
            {
                Random random = new Random();
                for (int i = 0; i <= 30; i++)
                {
                    int[] IPInts = { random.Next(256), random.Next(256), 
                        random.Next(256), random.Next(128) };
                    int portInt = random.Next(65535) + 1;
                    long addressLong = (long)(
                        IPInts[0]
                        + IPInts[1] * 256
                        + IPInts[2] * 256 * 256
                        + IPInts[3] * 256 * 256 * 256);
                    Log.Comment("Random IP " + IPInts[0] + "." + IPInts[1]
                        + "." + IPInts[2] + "." + IPInts[3] + ":" + portInt);
                    IPAddress address = new IPAddress(addressLong);

                    Log.Comment("EndPoint1 created with IPAddress and int");
                    IPEndPoint endPoint1 = new IPEndPoint(address,portInt);
                    Log.Comment("EndPoint2 created with long and int"); 
                    IPEndPoint endPoint2 = new IPEndPoint(addressLong, portInt);
                    if (endPoint1 == null)
                        throw new Exception("EndPoint1 is null");
                    if (endPoint2 == null)
                        throw new Exception("EndPoint2 is null");

                    Type typeOfEndPoint = endPoint1.GetType();
                    if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint"))
                        throw new Exception("EndPoint1 Type is incorrect");
                    typeOfEndPoint = endPoint2.GetType();
                    if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint"))
                        throw new Exception("EndPoint2 Type is incorrect");

                    if (endPoint1.ToString() != endPoint2.ToString())
                        throw new Exception("ToString returns differently for same data");

                    if (!endPoint1.Equals(endPoint2))
                    {
                        throw new Exception("Equals returns false for same data");
                    }


                    int hashCode1 = endPoint1.GetHashCode();
                    int hashCode2 = endPoint2.GetHashCode();


                    if (hashCode1 != hashCode2)
                        throw new Exception("GetHasCode returns differently for same data");

                    if (endPoint1.Address.ToString() != endPoint2.Address.ToString()
                        || endPoint1.Address.ToString() != address.ToString()
                        || endPoint2.Address.ToString() != address.ToString())
                        throw new Exception("Address returns wrong data");

                    if (endPoint1.Port != endPoint2.Port
                        || endPoint1.Port != portInt
                        || endPoint2.Port != portInt)
                        throw new Exception("Port returns wrong data");
                    
                    Log.Comment("Cloning Enpoint1 into EndPoint2");
                    endPoint2 = (IPEndPoint)endPoint2.Create(endPoint1.Serialize());
                    typeOfEndPoint = endPoint2.GetType();
                    if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint"))
                        throw new Exception("EndPoint2 Type is incorrect after clone");

                    if (endPoint1.ToString() != endPoint2.ToString())
                        throw new Exception("ToString returns differently for cloned data");


                    //21295	GetHashCode returns differently for cloned data
                    if (endPoint1.GetHashCode() != endPoint2.GetHashCode())
                        throw new Exception("GetHashCode returns differently for cloned data");

                    if (endPoint1.Address.ToString() != endPoint2.Address.ToString()
                        || endPoint1.Address.ToString() != address.ToString()
                        || endPoint2.Address.ToString() != address.ToString())
                        throw new Exception("Address returns wrong data after clone");

                    if (endPoint1.Port != endPoint2.Port
                        || endPoint1.Port != portInt
                        || endPoint2.Port != portInt)
                        throw new Exception("Port returns wrong data after clone");

                    Log.Comment("Recreating EndPoint2 with new data");
                    int portInt2 = portInt % 2 + 1;
                    long addressLong2 = (long)(
                        (IPInts[0] % 2 + 1)
                        + (IPInts[1] % 2 + 1 )* 256
                        + (IPInts[2] % 2 + 1 )* 256 * 256
                        + (IPInts[3] % 2 + 1 )* 256 * 256 * 256);
                    endPoint2 = new IPEndPoint(addressLong2, portInt2);

                    if (endPoint1.GetHashCode() == endPoint2.GetHashCode())
                        throw new Exception("GetHashCode returns same for " 
                            + endPoint1.ToString()
                            + " as " + endPoint2.ToString());

                    if (endPoint1.Address == endPoint2.Address
                        || endPoint2.Address == address)
                        throw new Exception("Address returns wrong data after change");

                    if (endPoint1.Port == endPoint2.Port
                        || endPoint2.Port == portInt)
                        throw new Exception("Port returns wrong data after change");
                }
            }
            catch (Exception e)
            {
                Log.Comment("Caught exception: " + e.Message);
                testResult = false;
            }
            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
示例#8
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");
		}
示例#9
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");
		}
        /// <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");
            }
        }
 public unsafe string sortIpAddressList(string IPAddressList)
 {
     string str;
     if ((IPAddressList == null) || (IPAddressList.Length == 0))
     {
         return string.Empty;
     }
     string[] strArray = IPAddressList.Split(new char[] { ';' });
     if (strArray.Length > MAX_IPADDRESS_LIST_LENGTH)
     {
         throw new ArgumentException(string.Format(SR.GetString("net_max_ip_address_list_length_exceeded"), MAX_IPADDRESS_LIST_LENGTH), "IPAddressList");
     }
     if (strArray.Length == 1)
     {
         return IPAddressList;
     }
     SocketAddress[] addressArray = new SocketAddress[strArray.Length];
     for (int i = 0; i < strArray.Length; i++)
     {
         strArray[i] = strArray[i].Trim();
         if (strArray[i].Length == 0)
         {
             throw new ArgumentException(SR.GetString("dns_bad_ip_address"), "IPAddressList");
         }
         SocketAddress address = new SocketAddress(AddressFamily.InterNetworkV6, 0x1c);
         if (UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(strArray[i], AddressFamily.InterNetworkV6, IntPtr.Zero, address.m_Buffer, ref address.m_Size) != SocketError.Success)
         {
             SocketAddress socketAddress = new SocketAddress(AddressFamily.InterNetwork, 0x10);
             if (UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(strArray[i], AddressFamily.InterNetwork, IntPtr.Zero, socketAddress.m_Buffer, ref socketAddress.m_Size) != SocketError.Success)
             {
                 throw new ArgumentException(SR.GetString("dns_bad_ip_address"), "IPAddressList");
             }
             IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
             IPEndPoint point2 = (IPEndPoint) point.Create(socketAddress);
             byte[] addressBytes = point2.Address.GetAddressBytes();
             byte[] buffer2 = new byte[0x10];
             for (int k = 0; k < 10; k++)
             {
                 buffer2[k] = 0;
             }
             buffer2[10] = 0xff;
             buffer2[11] = 0xff;
             buffer2[12] = addressBytes[0];
             buffer2[13] = addressBytes[1];
             buffer2[14] = addressBytes[2];
             buffer2[15] = addressBytes[3];
             IPAddress address3 = new IPAddress(buffer2);
             address = new IPEndPoint(address3, point2.Port).Serialize();
         }
         addressArray[i] = address;
     }
     int cb = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST)) + ((addressArray.Length - 1) * Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS)));
     Dictionary<IntPtr, KeyValuePair<SocketAddress, string>> dictionary = new Dictionary<IntPtr, KeyValuePair<SocketAddress, string>>();
     GCHandle[] handleArray = new GCHandle[addressArray.Length];
     for (int j = 0; j < addressArray.Length; j++)
     {
         handleArray[j] = GCHandle.Alloc(addressArray[j].m_Buffer, GCHandleType.Pinned);
     }
     IntPtr optionInValue = Marshal.AllocHGlobal(cb);
     try
     {
         UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST* socket_address_listPtr = (UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST*) optionInValue;
         socket_address_listPtr->iAddressCount = addressArray.Length;
         UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS* socket_addressPtr = &socket_address_listPtr->Addresses;
         for (int m = 0; m < socket_address_listPtr->iAddressCount; m++)
         {
             socket_addressPtr[m].iSockaddrLength = 0x1c;
             socket_addressPtr[m].lpSockAddr = handleArray[m].AddrOfPinnedObject();
             dictionary[socket_addressPtr[m].lpSockAddr] = new KeyValuePair<SocketAddress, string>(addressArray[m], strArray[m]);
         }
         new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp).IOControl(IOControlCode.AddressListSort, optionInValue, cb, optionInValue, cb);
         StringBuilder builder = new StringBuilder();
         for (int n = 0; n < socket_address_listPtr->iAddressCount; n++)
         {
             IntPtr lpSockAddr = socket_addressPtr[n].lpSockAddr;
             KeyValuePair<SocketAddress, string> pair = dictionary[lpSockAddr];
             builder.Append(pair.Value);
             if (n != (socket_address_listPtr->iAddressCount - 1))
             {
                 builder.Append(";");
             }
         }
         str = builder.ToString();
     }
     finally
     {
         if (optionInValue != IntPtr.Zero)
         {
             Marshal.FreeHGlobal(optionInValue);
         }
         for (int num7 = 0; num7 < handleArray.Length; num7++)
         {
             if (handleArray[num7].IsAllocated)
             {
                 handleArray[num7].Free();
             }
         }
     }
     return str;
 }
示例#12
0
        public unsafe string sortIpAddressList(string IPAddressList)
        {
            string str;

            if ((IPAddressList == null) || (IPAddressList.Length == 0))
            {
                return(string.Empty);
            }
            string[] strArray = IPAddressList.Split(new char[] { ';' });
            if (strArray.Length > MAX_IPADDRESS_LIST_LENGTH)
            {
                throw new ArgumentException(string.Format(SR.GetString("net_max_ip_address_list_length_exceeded"), MAX_IPADDRESS_LIST_LENGTH), "IPAddressList");
            }
            if (strArray.Length == 1)
            {
                return(IPAddressList);
            }
            SocketAddress[] addressArray = new SocketAddress[strArray.Length];
            for (int i = 0; i < strArray.Length; i++)
            {
                strArray[i] = strArray[i].Trim();
                if (strArray[i].Length == 0)
                {
                    throw new ArgumentException(SR.GetString("dns_bad_ip_address"), "IPAddressList");
                }
                SocketAddress address = new SocketAddress(AddressFamily.InterNetworkV6, 0x1c);
                if (UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(strArray[i], AddressFamily.InterNetworkV6, IntPtr.Zero, address.m_Buffer, ref address.m_Size) != SocketError.Success)
                {
                    SocketAddress socketAddress = new SocketAddress(AddressFamily.InterNetwork, 0x10);
                    if (UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(strArray[i], AddressFamily.InterNetwork, IntPtr.Zero, socketAddress.m_Buffer, ref socketAddress.m_Size) != SocketError.Success)
                    {
                        throw new ArgumentException(SR.GetString("dns_bad_ip_address"), "IPAddressList");
                    }
                    IPEndPoint point        = new IPEndPoint(IPAddress.Any, 0);
                    IPEndPoint point2       = (IPEndPoint)point.Create(socketAddress);
                    byte[]     addressBytes = point2.Address.GetAddressBytes();
                    byte[]     buffer2      = new byte[0x10];
                    for (int k = 0; k < 10; k++)
                    {
                        buffer2[k] = 0;
                    }
                    buffer2[10] = 0xff;
                    buffer2[11] = 0xff;
                    buffer2[12] = addressBytes[0];
                    buffer2[13] = addressBytes[1];
                    buffer2[14] = addressBytes[2];
                    buffer2[15] = addressBytes[3];
                    IPAddress address3 = new IPAddress(buffer2);
                    address = new IPEndPoint(address3, point2.Port).Serialize();
                }
                addressArray[i] = address;
            }
            int cb = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST)) + ((addressArray.Length - 1) * Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS)));
            Dictionary <IntPtr, KeyValuePair <SocketAddress, string> > dictionary = new Dictionary <IntPtr, KeyValuePair <SocketAddress, string> >();

            GCHandle[] handleArray = new GCHandle[addressArray.Length];
            for (int j = 0; j < addressArray.Length; j++)
            {
                handleArray[j] = GCHandle.Alloc(addressArray[j].m_Buffer, GCHandleType.Pinned);
            }
            IntPtr optionInValue = Marshal.AllocHGlobal(cb);

            try
            {
                UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST *socket_address_listPtr = (UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST *)optionInValue;
                socket_address_listPtr->iAddressCount = addressArray.Length;
                UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS *socket_addressPtr = &socket_address_listPtr->Addresses;
                for (int m = 0; m < socket_address_listPtr->iAddressCount; m++)
                {
                    socket_addressPtr[m].iSockaddrLength        = 0x1c;
                    socket_addressPtr[m].lpSockAddr             = handleArray[m].AddrOfPinnedObject();
                    dictionary[socket_addressPtr[m].lpSockAddr] = new KeyValuePair <SocketAddress, string>(addressArray[m], strArray[m]);
                }
                new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp).IOControl(IOControlCode.AddressListSort, optionInValue, cb, optionInValue, cb);
                StringBuilder builder = new StringBuilder();
                for (int n = 0; n < socket_address_listPtr->iAddressCount; n++)
                {
                    IntPtr lpSockAddr = socket_addressPtr[n].lpSockAddr;
                    KeyValuePair <SocketAddress, string> pair = dictionary[lpSockAddr];
                    builder.Append(pair.Value);
                    if (n != (socket_address_listPtr->iAddressCount - 1))
                    {
                        builder.Append(";");
                    }
                }
                str = builder.ToString();
            }
            finally
            {
                if (optionInValue != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(optionInValue);
                }
                for (int num7 = 0; num7 < handleArray.Length; num7++)
                {
                    if (handleArray[num7].IsAllocated)
                    {
                        handleArray[num7].Free();
                    }
                }
            }
            return(str);
        }
        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);
        }
示例#14
0
 public override EndPoint Create(SocketAddress socketaddr)
 {
     return(mIPEndPoint.Create(socketaddr));
 }
示例#15
0
        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;
        }