Serialize() public method

public Serialize ( ) : SocketAddress
return SocketAddress
Ejemplo n.º 1
0
        private void Button1_Click(object sender, EventArgs e)
        {
            IPAddress  ipAddress;
            IPEndPoint ipEndPoint;

            txtResult.Text = "";

            try
            {
                // 將IP位址字串轉換為IPAddress類別
                ipAddress = IPAddress.Parse(txtIP.Text);
                // 建立IPEndPoint物件
                ipEndPoint = new System.Net.IPEndPoint(ipAddress, Int32.Parse(txtPort.Text));

                // 若IP位址為IPv4位址形態,則AddressFamily屬性回傳InterNetwork;若為IPv6位址形態,則回傳InterNetworkV6
                txtResult.Text = "Address Family: " + ipEndPoint.AddressFamily.ToString() + "\r\n";

                // 以IPEndPoint的Address與Port屬性取得IP位址及通訊埠
                txtResult.Text = txtResult.Text + "IP:Port: " + ipEndPoint.Address.ToString() + ":" + ipEndPoint.Port.ToString() + "\r\n";

                // 將IPEndPoint序列化為SocketAddress
                txtResult.Text = txtResult.Text + "SocketAddress 內容: " + ipEndPoint.Serialize().ToString() + "\r\n";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Ping the given host
        /// </summary>
        /// <param name="ip">The IP to ping</param>
        /// <param name="timeout">The timeout of the operation</param>
        /// <returns>True/false wether the host is alive or not</returns>
        public bool PingHost( IPAddress ip, int timeout )
        {
            EndPoint remote = new IPEndPoint( ip, 8 );
            SocketAddress sa = remote.Serialize();

            // send the echo request
            sock.SendTo( IcmpPacket.CreatePacket().GetBytes(), remote );
            sock.SetSocketOption( SocketOptionLevel.Socket,
                                  SocketOptionName.ReceiveTimeout, timeout );
            bool recv = false;
            byte[] bytes = new byte[MAX_ACCEPTED];
            while(!recv)
            {
                if( sock.ReceiveFrom( bytes, ref remote ) == SOCK_ERROR )
                {
                    sock.Close();
                    break; // not alive
                }
                else
                {
                    recv = true;
                }
            }
            sock.Close();
            return recv;
        }
Ejemplo n.º 3
0
 /// <summary>
 /// This routine converts an IPEndPoint into a byte array that represents the
 /// underlying sockaddr structure of the correct type. Currently this routine
 /// supports only IPv4 and IPv6 socket address structures.
 /// </summary>
 /// <param name="endPoint">IPEndPoint to convert to a binary form</param>
 /// <returns>Binary array of the serialized socket address structure</returns>
 public static byte[] GetSockaddrBytes( IPEndPoint endPoint )
 {
     SocketAddress socketAddress = endPoint.Serialize();
     byte[] sockaddrBytes;
     sockaddrBytes = new byte[socketAddress.Size];
     for( int i = 0 ; i < socketAddress.Size ; i++ )
     {
         sockaddrBytes[i] = socketAddress[i];
     }
     return sockaddrBytes;
 }
Ejemplo n.º 4
0
		/// <summary>
		/// Creates an unmanaged sockaddr structure to pass to a WinAPI function.
		/// </summary>
		/// <param name="ipEndPoint">IP address and port number</param>
		/// <returns>a handle for the structure. Use the AddrOfPinnedObject Method to get a stable pointer to the object. </returns>
		/// <remarks>When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. </remarks>
		public static GCHandle CreateSockaddrStructure(IPEndPoint ipEndPoint) {
			SocketAddress socketAddress = ipEndPoint.Serialize();

			// use an array of bytes instead of the sockaddr structure 
			byte[] sockAddrStructureBytes = new byte[socketAddress.Size];
			GCHandle sockAddrHandle = GCHandle.Alloc(sockAddrStructureBytes, GCHandleType.Pinned);
			for (int i = 0; i < socketAddress.Size; ++i) {
				sockAddrStructureBytes[i] = socketAddress[i];
			}
			return sockAddrHandle;
		}
Ejemplo n.º 5
0
        public void Write(IPEndPoint value)
        {
            SocketAddress socketAddress = value.Serialize();
            byte[] socketAddressBytes = new byte[28];

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

            this.Write(socketAddressBytes);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This routine converts an IPEndPoint into a byte array that represents the
        /// underlying sockaddr structure of the correct type. Currently this routine
        /// supports IPv4 and IPv6 socket address structures. A sockaddr structure
        /// InterNetwork (v4) could be { 2, 0, 0, 156, 207, 46, 197, 32, 0, 0, 0, 0, 0, 0, 0, 0 }.
        /// The first two bytes represents the address family, the next two bytes the
        /// port number in big-endian. The next 4 bytes are reserved for the ip-address.
        /// 
        /// The in6_addr structure represents an IPv6 internet address. This
        /// InterNetwork (v6) structure is longer and holds a 16 byte long ip-address.
        /// 
        /// This method will always return 32 bytes, padding from the right with zeros.
        /// </summary>
        /// <param name="endPoint">IPEndPoint to convert to a binary form</param>
        /// <returns>Binary array of the serialized socket address structure</returns>
        public static byte[] GetBytes(IPEndPoint endPoint)
        {
            SocketAddress socketAddress = endPoint.Serialize();

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

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

            byte[] buffer = new byte[32];

            Array.Copy(sockaddrBytes, buffer, socketAddress.Size);

            return buffer;
        }
Ejemplo n.º 7
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.º 8
0
 public static bool TryConnect(string ipString, int port)
 {
     if (!Initialized)
     {
         var wsaData = new WSAData();
         if (WSAStartup(0x0202, out wsaData) != 0) return false;
         m_Buffer = typeof(SocketAddress).GetField("m_Buffer", (BindingFlags.Instance | BindingFlags.NonPublic));
         Initialized = true;
     }
     IPAddress address;
     if (!IPAddress.TryParse(ipString, out address)) return false;
     if (!((port >= 0) && (port <= 0xffff))) return false;
     var remoteEP = new IPEndPoint(address, port);
     SocketAddress socketAddress = remoteEP.Serialize();
     IntPtr m_Handle = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, IntPtr.Zero, 0, 1 /*overlapped*/);
     if (m_Handle == new IntPtr(-1)) return false;
     new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, remoteEP.Address.ToString(), remoteEP.Port).Demand();
     var buf = (byte[])m_Buffer.GetValue(socketAddress);
     bool result = (WSAConnect(m_Handle, buf, socketAddress.Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == 0);
     closesocket(m_Handle);
     return result;
 }
Ejemplo n.º 9
0
        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");
	}
 /// <summary>
 /// Map the intercepted IPEndPoint to the LspSession.
 /// </summary>
 /// <param name="index">Intercepted IPEndPoint. </param>
 /// <param name="transportType">Tcp or Udp</param>
 /// <returns>Mapped LspSession</returns>
 private LspSessionInfoCollection this[IPEndPoint index, StackTransportType transportType]
 {
     get
     {
         string strKey = transportType.ToString() + index.Serialize().ToString();
         if (sessionMap.ContainsKey(strKey))
         {
             return sessionMap[strKey];
         }
         else
         {
             return null;
         }
     }
     set
     {
         string strKey = transportType.ToString() + index.Serialize().ToString();
         sessionMap[strKey] = value;
     }
 }
Ejemplo n.º 11
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();
				}				
			}

        }
Ejemplo n.º 12
0
 public override SocketAddress Serialize()
 {
     return(mIPEndPoint.Serialize());
 }
Ejemplo n.º 13
0
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="localEndPoint"></param>
        public override void Start(IPEndPoint localEndPoint)
        {
            if (localEndPoint == null) return;

            Socket listener = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

            listener.Bind(localEndPoint);
            // 可挂起连接队列的最大长度
            const Int32 m_backlog = 64;
            listener.Listen(m_backlog);
            //执行AcceptAsync所需的缓冲区必须至少为 2 * (sizeof(SOCKADDR_STORAGE) + 16) 字节。
            int acceptSize = 2 * (localEndPoint.Serialize().Size + 0x10);
            SocketAsyncEventArgs e = new SocketAsyncEventArgs();
            e.Completed += new EventHandler<SocketAsyncEventArgs>(IOCompleted);
            e.SetBuffer(new byte[acceptSize], 0, acceptSize);
            e.UserToken = this;
            lock (m_sockets)
            {
                m_sockets.Add(listener);
            }
            StartAccept(listener, e);
        }
Ejemplo n.º 14
0
			public void Connect ()
			{
				/* If result.EndPoint is non-null,
				 * this is the standard one-address
				 * connect attempt.  Otherwise
				 * Addresses must be non-null and
				 * contain a list of addresses to try
				 * to connect to; the first one to
				 * succeed causes the rest of the list
				 * to be ignored.
				 */
				if (result.EndPoint != null) {
					try {
						if (!result.Sock.Blocking) {
							int success;
							result.Sock.Poll (-1, SelectMode.SelectWrite, out success);
							if (success == 0) {
								result.Sock.seed_endpoint = result.EndPoint;
								result.Sock.connected = true;
							} else {
								result.Complete (new SocketException (success));
								return;
							}
						} else {
							result.Sock.seed_endpoint = result.EndPoint;
							result.Sock.Connect (result.EndPoint);
							result.Sock.connected = true;
						}
					} catch (Exception e) {
						result.Complete (e);
						return;
					}

					result.Complete ();
				} else if (result.Addresses != null) {
					int error = (int) SocketError.InProgress; // why?
					foreach(IPAddress address in result.Addresses) {
						IPEndPoint iep = new IPEndPoint (address, result.Port);
						SocketAddress serial = iep.Serialize ();
						Socket.Connect_internal (result.Sock.socket, serial, out error);
						if (error == 0) {
							result.Sock.connected = true;
							result.Sock.seed_endpoint = iep;
							result.Complete ();
							return;
						} else if (error != (int)SocketError.InProgress &&
							   error != (int)SocketError.WouldBlock) {
							continue;
						}

						if (!result.Sock.Blocking) {
							int success;
							result.Sock.Poll (-1, SelectMode.SelectWrite, out success);
							if (success == 0) {
								result.Sock.connected = true;
								result.Sock.seed_endpoint = iep;
								result.Complete ();
								return;
							}
						}
					}
					result.Complete (new SocketException (error));
				} else {
					result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
				}
			}
        /// <summary>
        /// get a replaced endpoint.<para/>
        /// if the localEndPoint (that specifies the server to listen at) is not available, 
        /// LSP will give another endpoint to listen at, and intercept the traffic.<para/>
        /// if the output bool value isLspHooked is set to true, user must invoke the InterceptTraffic.
        /// </summary>
        /// <param name="transportType">
        /// a StackTransportType that specifies the type of transport. it must be Tcp or Udp.
        /// </param>
        /// <param name="localEndPoint">
        /// an IPEndPoint object that specifies the local endpoint for server to listen at.
        /// </param>
        /// <param name="isLspHooked">
        /// output a bool value that specifies whether LSP work.<para/>
        /// if true, must invoke InterceptTraffic.
        /// </param>
        /// <param name="isBlocking">
        /// output a bool value that specifies whether LSP is block mode.<para/>
        /// it's used to pass to InterceptTraffic.
        /// </param>
        /// <returns>
        /// return an IPEndPoint object that specifies the replaced endpoint.
        /// </returns>
        internal IPEndPoint GetReplacedEndPoint(
            StackTransportType transportType, IPEndPoint localEndPoint, out bool isLspHooked, out bool isBlocking)
        {
            if (disposed)
            {
                isLspHooked = false;
                isBlocking = false;

                return localEndPoint;
            }

            IPEndPoint replacedEndpoint;

            isBlocking = false;

            string strKey = transportType.ToString() + localEndPoint.Serialize().ToString();
            if (endPointsToHook.ContainsKey(strKey))
            {
                replacedEndpoint = new IPEndPoint(localEndPoint.Address, 0);
                //sdk local listening endpoint address is fixed as loopback address
                if (replacedEndpoint.AddressFamily == AddressFamily.InterNetwork)
                {
                    replacedEndpoint.Address = IPAddress.Loopback;
                }
                else
                {
                    replacedEndpoint.Address = IPAddress.IPv6Loopback;
                }
                isBlocking = endPointsToHook[strKey];
                endPointsToHook.Remove(strKey);
                isLspHooked = true;
            }
            else
            {
                replacedEndpoint = localEndPoint;
                isLspHooked = false;
            }

            return replacedEndpoint;
        }
Ejemplo n.º 16
0
        public MFTestResults NetTest6_SocketAddressBasic()
        {
            /// <summary>
            /// 1. Creates 30 Random IPs between 0.0.0.0 and 255.255.255.127
            /// 2. Verifies that they can be constructed as SocketAddress
            /// 3. Verifies that they have the correct data (GetAddressBytes)
            /// 4. Verifies ToString and GetHashcode
            /// </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) };
                    Log.Comment("Random IP " + IPInts[0] + "." + IPInts[1]
                        + "." + IPInts[2] + "." + IPInts[3]);
                    IPAddress address = new IPAddress((long)(
                        IPInts[0]
                        + IPInts[1] * 256
                        + IPInts[2] * 256 * 256
                        + IPInts[3] * 256 * 256 * 256));
                    int portInt = random.Next(65536);
                    IPEndPoint ipEndpoint1 = new IPEndPoint(address, portInt);
                    SocketAddress socketAddress1 = ipEndpoint1.Serialize();
                    SocketAddress socketAddress2 = ipEndpoint1.Serialize();
                    if (socketAddress1 == null)
                        throw new Exception("socketAddress1 is null");
                    if (socketAddress2 == null)
                        throw new Exception("socketAddress2 is null");

                    Type typeOfSocketAddress = socketAddress1.GetType();
                    if (typeOfSocketAddress != Type.GetType("System.Net.SocketAddress"))
                        throw new Exception("socketAddress1 Type is incorrect");
                    typeOfSocketAddress = socketAddress2.GetType();
                    if (typeOfSocketAddress != Type.GetType("System.Net.SocketAddress"))
                        throw new Exception("socketAddress2 Type is incorrect");

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

                    //21295	GetHashCode returns differently for cloned data
                    if (socketAddress1.GetHashCode() != socketAddress2.GetHashCode())
                        throw new Exception("GetHashCode returns differently for same data");

                    if (socketAddress1.Family != AddressFamily.InterNetwork) 
                        throw new Exception("socketAddress1 Family is incorrect");

                    if (socketAddress2.Family != AddressFamily.InterNetwork)
                        throw new Exception("socketAddress2 Family is incorrect");
                    /*
                     * Pending Resolution of 17428
                     * 
                    Log.Comment("Recreating socketAddress2 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);

                    IPEndPoint ipEndpoint2 = new IPEndPoint(addressLong2, portInt2);
                    socketAddress2 = ipEndpoint2.Serialize();
                    socketAddress2.Family = AddressFamily.Chaos;
                    */
                    socketAddress2 = new SocketAddress(AddressFamily.Chaos, 8);
                    if (socketAddress1.GetHashCode() == socketAddress2.GetHashCode())
                        throw new Exception("GetHashCode returns same for " 
                            + socketAddress1.ToString()
                            + " as " + socketAddress2.ToString());

                    if (socketAddress1.ToString() == socketAddress2.ToString())
                        throw new Exception("ToString returns same for different data"); 
                }
            }
            catch (Exception e)
            {
                Log.Comment("Caught exception: " + e.Message);
                testResult = false;
            }
            return (testResult ? MFTestResults.Pass : MFTestResults.KnownFailure);
        }
        public static void fSocketAddress()
        {
            IPAddress ipAddr1 = IPAddress.Parse("127.0.0.1");
            IPAddress ipAddr2 = IPAddress.Parse("::1");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr1, 80);

            SocketAddress SocketAddr = ipEndPoint.Serialize();

            MessageBox.Show(SocketAddr.ToString());
        }
        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);
        }
        /// <summary>
        /// Intercept the ip traffic in a designated address. All the traffic will be sent to sdkListeningIpAddress. 
        /// </summary>
        /// <param name="transportType">TCP or UDP . </param>
        /// <param name="isBlocking">Whether this request is a blocking request.</param>
        /// <param name="interceptedEndPoint">The intercepted IP/Port of the windows service . </param>
        internal void InterceptTraffic(StackTransportType transportType, bool isBlocking, IPEndPoint interceptedEndPoint)
        {
            if (disposed)
            {
                return;
            }

            string strKey = transportType.ToString() + interceptedEndPoint.Serialize().ToString();
            endPointsToHook[strKey] = isBlocking;
        }
        /// <summary>
        /// Bind the local and remote IPEndPoint.
        /// for tcp: map from lsp dll tcp endpoint to the real tcp endpoint
        /// for udp: map from the real udp endpoint to lsp dll udp endpoint
        /// </summary>
        /// <param name="localEndpoint">Local server endpoint of sdk</param>
        /// <param name="srcEndPoint">the tcp/udp endpoint</param>
        /// <param name="mappedEndPoint">the tcp/udp endpoint </param>
        /// <param name="transportType">Tcp or Udp </param>
        internal void SetMappedIPEndPoint(IPEndPoint localEndpoint, IPEndPoint srcEndPoint,
            IPEndPoint mappedEndPoint, StackTransportType transportType)
        {
            if (disposed)
            {
                return;
            }

            Dictionary<string, IPEndPoint> endPointMap;

            IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);

            string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();
            if (sessionMap.ContainsKey(strKey))
            {
                endPointMap = sessionMap[strKey].endPoints;
            }
            else
            {
                return;
            }

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

            //For tcp, each endpoint-to-endpoint pair has two records in the dictionary.
            if (transportType == StackTransportType.Tcp)
            {
                strKey = mappedEndPoint.Serialize().ToString();
                endPointMap[strKey] = srcEndPoint;
            }
        }
Ejemplo n.º 21
0
        // internal method responsible for sending echo request on win2k and higher

        private PingReply InternalSend (IPAddress address, byte[] buffer, int timeout, PingOptions options, bool async) {
                        
            ipv6 =  (address.AddressFamily == AddressFamily.InterNetworkV6)?true:false;
            sendSize = buffer.Length;

            //get and cache correct handle
            if (!ipv6 && handlePingV4 == null) {
                handlePingV4 = UnsafeNetInfoNativeMethods.IcmpCreateFile ();
                if (handlePingV4.IsInvalid) {
                    handlePingV4 = null;
                    throw new Win32Exception(); // Gets last error
                }
            }
            else if (ipv6 && handlePingV6 == null) {
                handlePingV6 = UnsafeNetInfoNativeMethods.Icmp6CreateFile();
                if (handlePingV6.IsInvalid) {
                    handlePingV6 = null;
                    throw new Win32Exception(); // Gets last error
                }
            }


            //setup the options
            IPOptions ipOptions = new IPOptions (options);

            //setup the reply buffer
            if (replyBuffer == null) {
                replyBuffer = SafeLocalFree.LocalAlloc (MaxUdpPacket);
            }

            //queue the event
            int error;

            try
            {
                if (async) {
                    if (pingEvent == null)
                        pingEvent = new ManualResetEvent (false);
                    else
                        pingEvent.Reset();
                
                    registeredWait = ThreadPool.RegisterWaitForSingleObject (pingEvent, new WaitOrTimerCallback (PingCallback), this, -1, true);
                }

                //Copy user dfata into the native world
                SetUnmanagedStructures (buffer);

                if (!ipv6) {
                    if (async) {
                        error = (int)UnsafeNetInfoNativeMethods.IcmpSendEcho2 (handlePingV4, pingEvent.SafeWaitHandle, IntPtr.Zero, IntPtr.Zero, (uint)address.m_Address, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                    else{
                        error = (int)UnsafeNetInfoNativeMethods.IcmpSendEcho2 (handlePingV4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, (uint)address.m_Address, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                }
                else {                                                   
                    IPEndPoint ep = new IPEndPoint (address, 0);
                    SocketAddress remoteAddr = ep.Serialize ();
                    byte[] sourceAddr = new byte[28];
                    if(async){
                        error = (int)UnsafeNetInfoNativeMethods.Icmp6SendEcho2 (handlePingV6, pingEvent.SafeWaitHandle, IntPtr.Zero, IntPtr.Zero, sourceAddr, remoteAddr.m_Buffer, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                    else{
                        error = (int)UnsafeNetInfoNativeMethods.Icmp6SendEcho2 (handlePingV6, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, sourceAddr, remoteAddr.m_Buffer, requestBuffer, (ushort)buffer.Length, ref ipOptions, replyBuffer, MaxUdpPacket, (uint)timeout);
                    }
                }
            }
            catch
            {
                UnregisterWaitHandle();
                throw;
            }

            //need this if something is bogus.
            if (error == 0) {
                error = (int)Marshal.GetLastWin32Error();
                
                // Only skip Async IO Pending error value
                if (async && error == UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
                    return null; // Expected async return value
                
                // Cleanup
                FreeUnmanagedStructures();
                UnregisterWaitHandle();

                if (async // No IPStatus async errors
                    || error < (int)IPStatus.DestinationNetworkUnreachable // Min
                    || error > (int)IPStatus.DestinationScopeMismatch) // Max // Out of IPStatus range
                    throw new Win32Exception(error);

                return new PingReply((IPStatus)error); // Synchronous IPStatus errors 
            }

            if (async) {
                return null;
            }

            FreeUnmanagedStructures ();

            //return the reply
            PingReply reply;
            if (ipv6) {
                Icmp6EchoReply icmp6Reply = (Icmp6EchoReply)Marshal.PtrToStructure(replyBuffer.DangerousGetHandle(), typeof(Icmp6EchoReply));
                reply = new PingReply(icmp6Reply, replyBuffer.DangerousGetHandle(), sendSize);
            }
            else {
                IcmpEchoReply icmpReply = (IcmpEchoReply)Marshal.PtrToStructure(replyBuffer.DangerousGetHandle(), typeof(IcmpEchoReply));
                reply = new PingReply(icmpReply);
            }

            // IcmpEchoReply still has an unsafe IntPtr reference into replybuffer
            // and replybuffer was being freed prematurely by the GC, causing AccessViolationExceptions.
            GC.KeepAlive(replyBuffer);

            return reply;
        }
Ejemplo n.º 22
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");
		}
        /// <summary>
        /// Get the local IPEndPoint by remote IPEndPoint. The key is remote IPEndPoint.
        /// for tcp: map from lsp dll tcp endpoint to the real tcp endpoint
        /// for udp: map from the real udp endpoint to lsp dll udp endpoint
        /// </summary>
        /// <param name="localEndpoint">Local server endpoint of sdk</param>
        /// <param name="srcEndPoint">source endpoint</param>
        /// <param name="transportType">tcp or udp</param>
        /// <returns>Local LspClient socket</returns>
        internal IPEndPoint GetMappedIPEndPoint(IPEndPoint localEndpoint, IPEndPoint srcEndPoint, StackTransportType transportType)
        {
            if (disposed)
            {
                return null;
            }

            Dictionary<string, IPEndPoint> endPointMap;

            IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);

            string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();
            if (sessionMap.ContainsKey(strKey))
            {
                endPointMap = sessionMap[strKey].endPoints;
            }
            else
            {
                return null;
            }

            strKey = srcEndPoint.Serialize().ToString();
            if (endPointMap.ContainsKey(strKey))
            {
                return endPointMap[strKey];
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
0
        private static byte[] GetNativeSocketAddress(IPEndPoint ipEp, out int sockaddrLen)
        {
            var sockaddr = ipEp.Serialize();
            sockaddrLen = sockaddr.Size;
            var addrbuf = new byte[(sockaddrLen / IntPtr.Size + 2) * IntPtr.Size]; //sizeof DWORD

            // Address Family serialization
            addrbuf[0] = sockaddr[0];
            addrbuf[1] = sockaddr[1];

            // Port serialization
            addrbuf[2] = sockaddr[2];
            addrbuf[3] = sockaddr[3];

            // IPv4 Address serialization
            addrbuf[4] = sockaddr[4];
            addrbuf[5] = sockaddr[5];
            addrbuf[6] = sockaddr[6];
            addrbuf[7] = sockaddr[7];
            return addrbuf;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Test TCP client
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine("TCP client.");
            Console.WriteLine();
            Console.WriteLine("|--- \"exit\" to exit.                                  ---|");
            Console.WriteLine("|--- \"start {cn}\" to start {cn} number of connections.---|");
            Console.WriteLine();
            Console.Write("Please enter remote address and port: ");
            bool portReady = false;
            string line = Console.ReadLine();

            // input management stuff. boring.

            while (line != "exit")
            {
                if (!portReady)
                {
                    try
                    {
                        string[] ss = line.Split(':');
                        port = int.Parse(ss[1]);
                        IPAddress add = IPAddress.Parse(ss[0]);
                        clientEndpoint = new IPEndPoint(add, port);
                        address = clientEndpoint.Serialize().ToString();
                        if (port > short.MaxValue || port < 2)
                        {
                            Console.WriteLine("Invalid port.");
                            Console.Write("Please enter remote address and port: ");
                        }
                        else
                        {
                            Start();
                            portReady = true;
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Invalid address.");
                        Console.Write("Please enter remote address and port: ");
                    }
                }
                else
                {
                    if (line.StartsWith("start "))
                    {
                        int count = 0;
                        try
                        {
                            count = int.Parse(line.Substring("start ".Length));
                        }
                        catch { }
                        Console.WriteLine("Starting " + count + " connections.");
                        for (int i = 0; i < count; i++)
                        {
                            // this starts another connection
                            Start();
                        }
                    }
                    else
                    {
                        try
                        {
                            byte[] bytes = Encoding.UTF8.GetBytes(line + "\n");
                            lock (socketList)
                            {
                                foreach (SocketInfo info in socketList)
                                {
                                    info.socket.Send(bytes, bytes.Length, SocketFlags.None);
                                }
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Unable to send data. Connection lost.");
                        }
                    }
                }
                line = Console.ReadLine();
            }
            Console.Write("Shutting down client... ");
            try
            {
                lock (socketList)
                {
                    for (int i = socketList.Count - 1; i >= 0; i--)
                    {
                        try {
                            socketList[i].socket.Shutdown(SocketShutdown.Both);
                            socketList[i].socket.Close();
                        } catch {}
                        socketList.RemoveAt(i);
                    }
                }
            }
            catch { }
            Console.WriteLine("Bye.");
            Thread.Sleep(500);
        }
Ejemplo n.º 27
0
        private void HandleFragment(byte[] packetData, IPEndPoint from, LCMDataInputStream ins)
		{
			int msgSeqNumber = ins.ReadInt32();
			int msgSize = ins.ReadInt32() & unchecked((int) 0xffffffff);
			int fragmentOffset = ins.ReadInt32() & unchecked((int) 0xffffffff);
			int fragmentId = ins.ReadInt16() & 0xffff;
			int fragmentsInMsg = ins.ReadInt16() & 0xffff;
			
			// read entire packet payload
			byte[] payload = new byte[ins.Available];
			ins.ReadFully(payload);
			
			if (ins.Available > 0)
			{
				System.Console.Error.WriteLine("Unread data! " + ins.Available);
			}
			
			int dataStart = 0;
			int fragSize = payload.Length;
			
			FragmentBuffer fbuf;
            fragBufs.TryGetValue(from.Serialize(), out fbuf);
			
			if (fbuf != null && ((fbuf.msgSeqNumber != msgSeqNumber) || (fbuf.data_size != msgSize)))
			{
                fragBufs.Remove(fbuf.from);
				fbuf = null;
			}
			
			if (fbuf == null && fragmentId == 0)
			{	
				// extract channel name
				int channelLen = 0;
				for (; channelLen < payload.Length; channelLen++)
				{
					if (payload[channelLen] == 0)
					{
						break;
					}
				}

				dataStart = channelLen + 1;
				fragSize -= (channelLen + 1);
				string tempStr;
				tempStr = System.Text.Encoding.GetEncoding("US-ASCII").GetString(payload);
				string channel = new string(tempStr.ToCharArray(), 0, channelLen);

                fbuf = new FragmentBuffer(from.Serialize(), channel, msgSeqNumber, msgSize, fragmentsInMsg);

                fragBufs.Add(fbuf.from, fbuf);
			}
			
			if (fbuf == null)
			{
				// TODO
				return ;
			}
			
			if (fragmentOffset + fragSize > fbuf.data_size)
			{
				System.Console.Error.WriteLine("LC: dropping invalid fragment");
                fragBufs.Remove(fbuf.from);
				return ;
			}
			
			Array.Copy(payload, dataStart, fbuf.data, fragmentOffset, fragSize);
			fbuf.fragments_remaining--;
			
			if (0 == fbuf.fragments_remaining)
			{
				lcm.ReceiveMessage(fbuf.channel, fbuf.data, 0, fbuf.data_size);
                fragBufs.Remove(fbuf.from);
			}
		}
Ejemplo n.º 28
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();
                    }
                }
            }
        }
        private static SOCKADDR_STORAGE CreateSockAddrStorageStructure(int port)
        {
            var result = new SOCKADDR_STORAGE();
            result.ss_family = (short)AddressFamily.InterNetwork;
            var ipEndPoint = new IPEndPoint(IPAddress.Any, port);
            var socketAddress = ipEndPoint.Serialize();
            result.__ss_pad1 = new byte[6];
            for (var i = 0; i < result.__ss_pad1.Length; i++)
            {
                result.__ss_pad1[i] = socketAddress[i + 2];
            }

            return result;
        }
Ejemplo n.º 30
0
		public void Connect (IPAddress[] addresses, int port)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (addresses == null)
				throw new ArgumentNullException ("addresses");

			if (this.AddressFamily != AddressFamily.InterNetwork &&
				this.AddressFamily != AddressFamily.InterNetworkV6)
				throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");

			if (islistening)
				throw new InvalidOperationException ();

			/* FIXME: do non-blocking sockets Poll here? */
			int error = 0;
			foreach (IPAddress address in addresses) {
				IPEndPoint iep = new IPEndPoint (address, port);
				SocketAddress serial = iep.Serialize ();
				
				Connect_internal (socket, serial, out error);
				if (error == 0) {
					connected = true;
					isbound = true;
					seed_endpoint = iep;
					return;
				} else if (error != (int)SocketError.InProgress &&
					   error != (int)SocketError.WouldBlock) {
					continue;
				}
				
				if (!blocking) {
					Poll (-1, SelectMode.SelectWrite);
					error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
					if (error == 0) {
						connected = true;
						isbound = true;
						seed_endpoint = iep;
						return;
					}
				}
			}
			if (error != 0)
				throw new SocketException (error);
		}
        /// <summary>
        /// Disconnect the remote EndPoint, and clean up the resources.
        /// </summary>
        /// <param name="localEndpoint">SDK listening endpoint</param>
        /// <param name="remoteEndpoint">the endpoint of real remote client</param>
        /// <param name="transportType">Tcp or Udp</param>
        internal void Disconnect(IPEndPoint localEndpoint, IPEndPoint remoteEndpoint, 
            StackTransportType transportType)
        {
            if (disposed)
            {
                return;
            }

            IPEndPoint connectableEndpoint = GetConnectableEndpoint(localEndpoint);

            string strKey = transportType.ToString() + connectableEndpoint.Serialize().ToString();
            if (sessionMap.ContainsKey(strKey))
            {
                Dictionary<string, IPEndPoint> endPointMap =
                    sessionMap[strKey].endPoints;
                strKey = remoteEndpoint.Serialize().ToString();
                if (transportType == StackTransportType.Udp)
                {
                    endPointMap.Remove(strKey);
                }
                else
                {
                    //For tcp, each endpoint-to-endpoint pair has two records in the dictionary.
                    IPEndPoint mappedEndpoint = endPointMap[strKey];
                    endPointMap.Remove(strKey);
                    endPointMap.Remove(mappedEndpoint.Serialize().ToString());
                }
            }
        }
Ejemplo n.º 32
0
		public void Connect (IPAddress[] addresses, int port)
		{
			ThrowIfDisposedAndClosed ();

			if (addresses == null)
				throw new ArgumentNullException ("addresses");
			if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
				throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
			if (is_listening)
				throw new InvalidOperationException ();

			// FIXME: do non-blocking sockets Poll here?
			int error = 0;
			foreach (IPAddress address in addresses) {
				IPEndPoint iep = new IPEndPoint (address, port);

				Connect_internal (safe_handle, iep.Serialize (), out error);
				if (error == 0) {
					is_connected = true;
					is_bound = true;
					seed_endpoint = iep;
					return;
				}
				if (error != (int)SocketError.InProgress && error != (int)SocketError.WouldBlock)
					continue;

				if (!is_blocking) {
					Poll (-1, SelectMode.SelectWrite);
					error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
					if (error == 0) {
						is_connected = true;
						is_bound = true;
						seed_endpoint = iep;
						return;
					}
				}
			}

			if (error != 0)
				throw new SocketException (error);
		}
Ejemplo n.º 33
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;
        }