Esempio n. 1
0
 public void Remove(Session session, SocketAddress address)
 {
     Session existing;
     _Sessions.TryRemove(address, out session);
     _SessionsByID.TryRemove(session.SessionID, out existing);
     _SessionList.Remove(session);
 }
        internal UnixDomainSocketEndPoint(SocketAddress socketAddress)
        {
            if (socketAddress == null)
            {
                throw new ArgumentNullException(nameof(socketAddress));
            }

            if (socketAddress.Family != EndPointAddressFamily ||
                socketAddress.Size > s_nativeAddressSize)
            {
                throw new ArgumentOutOfRangeException(nameof(socketAddress));
            }

            if (socketAddress.Size > s_nativePathOffset)
            {
                _encodedPath = new byte[socketAddress.Size - s_nativePathOffset];
                for (int i = 0; i < _encodedPath.Length; i++)
                {
                    _encodedPath[i] = socketAddress[s_nativePathOffset + i];
                }

                _path = s_pathEncoding.GetString(_encodedPath, 0, _encodedPath.Length);
            }
            else
            {
#if NET451
                _encodedPath = new byte[0];
#else
                _encodedPath = Array.Empty<byte>();
#endif
                _path = string.Empty;
            }
        }
Esempio n. 3
0
		public override EndPoint Create (SocketAddress socketAddress)
		{
			/*
			 * Should also check this
			 *
			int addr = (int) AddressFamily.Unix;
			if (socketAddress [0] != (addr & 0xFF))
				throw new ArgumentException ("socketAddress is not a unix socket address.");

			if (socketAddress [1] != ((addr & 0xFF00) >> 8))
				throw new ArgumentException ("socketAddress is not a unix socket address.");
			 */

			if (socketAddress.Size == 2) {
				// Empty filename.
				// Probably from RemoteEndPoint which on linux does not return the file name.
				UnixEndPoint uep = new UnixEndPoint ("a");
				uep.filename = "";
				return uep;
			}
			byte [] bytes = new byte [socketAddress.Size - 2 - 1];
			for (int i = 0; i < bytes.Length; i++) {
				bytes [i] = socketAddress [i + 2];
			}

			string name = Encoding.Default.GetString (bytes);
			return new UnixEndPoint (name);
		}
Esempio n. 4
0
		public override EndPoint Create (SocketAddress socketAddress)
		{
			/*
			 * Should also check this
			 *
			int addr = (int) AddressFamily.Unix;
			if (socketAddress [0] != (addr & 0xFF))
				throw new ArgumentException ("socketAddress is not a unix socket address.");

			if (socketAddress [1] != ((addr & 0xFF00) >> 8))
				throw new ArgumentException ("socketAddress is not a unix socket address.");
			 */

			if (socketAddress.Size == 2) {
				// Empty filename.
				// Probably from RemoteEndPoint which on linux does not return the file name.
				UnixEndPoint uep = new UnixEndPoint ("a");
				uep.filename = "";
				return uep;
			}
			int size = socketAddress.Size - 2;
			byte [] bytes = new byte [size];
			for (int i = 0; i < bytes.Length; i++) {
				bytes [i] = socketAddress [i + 2];
				// There may be junk after the null terminator, so ignore it all.
				if (bytes [i] == 0) {
					size = i;
					break;
				}
			}

			string name = Encoding.Default.GetString (bytes, 0, size);
			return new UnixEndPoint (name);
		}
 public override SocketAddress Serialize()
 {
     if (this.m_Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
     {
         SocketAddress address = new SocketAddress(this.AddressFamily, 0x1c);
         int port = this.Port;
         address[2] = (byte) (port >> 8);
         address[3] = (byte) port;
         address[4] = 0;
         address[5] = 0;
         address[6] = 0;
         address[7] = 0;
         long scopeId = this.Address.ScopeId;
         address[0x18] = (byte) scopeId;
         address[0x19] = (byte) (scopeId >> 8);
         address[0x1a] = (byte) (scopeId >> 0x10);
         address[0x1b] = (byte) (scopeId >> 0x18);
         byte[] addressBytes = this.Address.GetAddressBytes();
         for (int i = 0; i < addressBytes.Length; i++)
         {
             address[8 + i] = addressBytes[i];
         }
         return address;
     }
     SocketAddress address2 = new SocketAddress(this.m_Address.AddressFamily, 0x10);
     address2[2] = (byte) (this.Port >> 8);
     address2[3] = (byte) this.Port;
     address2[4] = (byte) this.Address.m_Address;
     address2[5] = (byte) (this.Address.m_Address >> 8);
     address2[6] = (byte) (this.Address.m_Address >> 0x10);
     address2[7] = (byte) (this.Address.m_Address >> 0x18);
     return address2;
 }
Esempio n. 6
0
        public override EndPoint Create(SocketAddress socketAddress)
        {
            // strip out of SocketAddress information on the EndPoint
            //

            byte[] buf = socketAddress.m_Buffer;

            Debug.Assert(socketAddress.Family == AddressFamily.InterNetwork);

            int port = (int)(
                    (buf[2] << 8 & 0xFF00) |
                    (buf[3])
                    );

            long address = (long)(
                    (buf[4] & 0x000000FF) |
                    (buf[5] << 8 & 0x0000FF00) |
                    (buf[6] << 16 & 0x00FF0000) |
                    (buf[7] << 24)
                    ) & 0x00000000FFFFFFFF;

            IPEndPoint created = new IPEndPoint(address, port);

            return created;
        }
Esempio n. 7
0
		public void AddSession(SocketAddress address, Session session)
		{
			if (_Sessions.TryAdd(address, session))
			{
				_SessionsByID.TryAdd(session.SessionID, session);
				_SessionList.Add(session);
			}
		}
        //
        // SetUnmanagedStructures -
        // Fills in Overlapped Structures used in an Async Overlapped Winsock call
        //   these calls are outside the runtime and are unmanaged code, so we need
        //   to prepare specific structures and ints that lie in unmanaged memory
        //   since the Overlapped calls can be Async
        //

        internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, SocketFlags socketFlags)
        {
            m_MessageBuffer = new byte[s_WSAMsgSize];
            m_WSABufferArray = new byte[s_WSABufferSize];

            //ipv4 or ipv6?
            IPAddress ipAddress = (socketAddress.Family == AddressFamily.InterNetworkV6 
                ? socketAddress.GetIPAddress() : null);
            bool ipv4 = (((Socket)AsyncObject).AddressFamily == AddressFamily.InterNetwork
                || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
            bool ipv6 = ((Socket)AsyncObject).AddressFamily == AddressFamily.InterNetworkV6;

            //prepare control buffer
            if (ipv4) {
                m_ControlBuffer = new byte[s_ControlDataSize];
            }
            else if (ipv6) {
                m_ControlBuffer = new byte[s_ControlDataIPv6Size];
            }

            //pin buffers
            object[] objectsToPin = new object[(m_ControlBuffer != null)?5:4];
            objectsToPin[0] = buffer;
            objectsToPin[1] = m_MessageBuffer;
            objectsToPin[2] = m_WSABufferArray;
            
            //prepare socketaddress buffer
            m_SocketAddress = socketAddress;
            m_SocketAddress.CopyAddressSizeIntoBuffer();
            objectsToPin[3] = m_SocketAddress.m_Buffer;
                
            if(m_ControlBuffer != null){
                objectsToPin[4] = m_ControlBuffer;
            }

            base.SetUnmanagedStructures(objectsToPin);

            //prepare data buffer
            m_WSABuffer = (WSABuffer*) Marshal.UnsafeAddrOfPinnedArrayElement(m_WSABufferArray, 0);
            m_WSABuffer->Length = size;
            m_WSABuffer->Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);


            //setup structure
            m_Message = (UnsafeNclNativeMethods.OSSOCK.WSAMsg*) Marshal.UnsafeAddrOfPinnedArrayElement(m_MessageBuffer, 0);
            m_Message->socketAddress = Marshal.UnsafeAddrOfPinnedArrayElement(m_SocketAddress.m_Buffer,0);
            m_Message->addressLength = (uint)m_SocketAddress.Size;
            m_Message->buffers = Marshal.UnsafeAddrOfPinnedArrayElement(m_WSABufferArray,0);
            m_Message->count = 1;

            if(m_ControlBuffer != null){
                m_Message->controlBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(m_ControlBuffer, 0);
                m_Message->controlBuffer.Length = m_ControlBuffer.Length;
            }

            m_Message->flags = socketFlags;
        }
    virtual public EndPoint Create(SocketAddress socketAddress)
    {
      Contract.Requires(socketAddress.Family == this.AddressFamily);
      Contract.Requires(socketAddress.Size >= 8);

      Contract.Ensures(Contract.Result<EndPoint>()!= null);

      return default(EndPoint);
    }
		private static int RecvFrom_internal(IntPtr sock,
		byte[] buffer,
		int offset,
		int count,
		SocketFlags flags,
		ref SocketAddress sockaddr,
		out int error)
		{
			throw new System.NotImplementedException();
		}
        private static int GetBestInterfaceForAddress(IPAddress addr) {
            int index;
            SocketAddress address = new SocketAddress(addr);
            int error = (int)UnsafeNetInfoNativeMethods.GetBestInterfaceEx(address.m_Buffer, out index);
            if (error != 0) {
                throw new NetworkInformationException(error);
            }

            return index;
        }
		public override SocketAddress Serialize ()
		{
			byte [] bytes = Encoding.Default.GetBytes (filename);
			SocketAddress sa = new SocketAddress (AddressFamily, bytes.Length + 2);
			// sa [0] -> family low byte, sa [1] -> family high byte
			for (int i = 0; i < bytes.Length; i++)
				sa [i + 2] = bytes [i];

			return sa;
		}
Esempio n. 13
0
        private static System.Net.SocketAddress GetNetSocketAddress(Internals.SocketAddress address)
        {
            var result = new System.Net.SocketAddress(address.Family, address.Size);

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

            return(result);
        }
Esempio n. 14
0
        public IPEndPoint ReadIPEndPoint()
        {
            SocketAddress socketAddress = new SocketAddress(AddressFamily.InterNetwork);
            byte[] socketAddressBytes = ReadBytes(28);

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

            return (IPEndPoint)new IPEndPoint(IPAddress.Any, 0).Create(socketAddress);
        }
Esempio n. 15
0
 public Rtp()
 {
     RtpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     SocketAddress sa = new SocketAddress(AddressFamily.InterNetwork);
     IPEndPoint ep = new IPEndPoint(IPAddress.Any, RtpPort);
     RtpSocket.Bind(ep);
     //IPEndPoint iep = (IPEndPoint)RtpSocket.LocalEndPoint;
     //ClientPort = iep.Port;
     //Logging.Log(string.Format("Ip Address {0}, Port {1}", iep.Address.ToString(), ClientPort));
     RtpEvntArgs = new SocketAsyncEventArgs();
     RtpEvntArgs.Completed += RtpEvntArgs_Completed;
 }
        public override SocketAddress Serialize()
        {
            var result = new SocketAddress(AddressFamily.Unix, s_nativeAddressSize);

            for (int index = 0; index < _encodedPath.Length; index++)
            {
                result[s_nativePathOffset + index] = _encodedPath[index];
            }
            result[s_nativePathOffset + _encodedPath.Length] = 0; // path must be null-terminated

            return result;
        }
Esempio n. 17
0
        public static Internals.SocketAddress Serialize(EndPoint endpoint)
        {
            Debug.Assert(!(endpoint is DnsEndPoint));

            var ipEndPoint = endpoint as IPEndPoint;

            if (ipEndPoint != null)
            {
                return(new Internals.SocketAddress(ipEndPoint.Address, ipEndPoint.Port));
            }

            System.Net.SocketAddress address = endpoint.Serialize();
            return(GetInternalSocketAddress(address));
        }
		public override SocketAddress Serialize()
		{
			// we add a byte (0 = raw, 1 = tls) to the SocketAddress generated by the base

			var tmp = base.Serialize();
			int count = tmp.Size;

			var sockAddr = new SocketAddress(this.AddressFamily, count + 1);

			for(int i=0;i<count;i++) sockAddr[i] = tmp[i];
			sockAddr[count] = m_tls ? (byte)1 : (byte)0;

			return sockAddr;
		}
Esempio n. 19
0
		public override EndPoint Create(SocketAddress sockaddr) {
			if (sockaddr.Size < 8) {
				return null;
			}
			if (sockaddr.Family != AddressFamily.InterNetwork) {
				// Only support IP4
				return null;
			}
			int port = (((int)sockaddr[2]) << 8) | (int)sockaddr[3];
			long address = (((long)sockaddr[7]) << 24) |
				(((long)sockaddr[6]) << 16) |
				(((long)sockaddr[5]) << 8) |
				(long)sockaddr[4];
			return new IPEndPoint(address, port);
		}
		public override EndPoint Create(SocketAddress socketAddress)
		{
			//note: this methods constructs a NEW endpoint, and does not change the current instance (why???)

			// Current implementation of IPEndPoint does really check the exact size of the buffer, and should not use the extra byte we added...
			// > Fix this if this is no longer the case in future .NET implementations (or Mono?)
			var tmp = (IPEndPoint)base.Create(socketAddress);

			bool tls = false;
			int count = socketAddress.Size;
			if ((socketAddress.Family == System.Net.Sockets.AddressFamily.InterNetwork && count == 17) || (socketAddress.Family == System.Net.Sockets.AddressFamily.InterNetworkV6 && count == 29))
			{
				tls = socketAddress[count - 1] != 0;
			}

			return new FdbEndPoint(tmp.Address, tmp.Port, tls);
		}
Esempio n. 21
0
        public static IPHostEntry GetHostEntry(string hostNameOrAddress)
        {

            //Do we need to try to pase this as an Address????
            string canonicalName;
            byte[][] addresses;

            NativeSocket.getaddrinfo(hostNameOrAddress, out canonicalName, out addresses);

            int cAddresses = addresses.Length;
            IPAddress[] ipAddresses = new IPAddress[cAddresses];
            IPHostEntry ipHostEntry = new IPHostEntry();

            for (int i = 0; i < cAddresses; i++)
            {
                byte[] address = addresses[i];

                SocketAddress sockAddress = new SocketAddress(address);

                AddressFamily family;

                if(SystemInfo.IsBigEndian)
                {
                    family = (AddressFamily)((address[0] << 8) | address[1]);
                }
                else
                {
                    family = (AddressFamily)((address[1] << 8) | address[0]);
                }
                //port address[2-3]

                if (family == AddressFamily.InterNetwork)
                {
                    //This only works with IPv4 addresses

                    uint ipAddr = (uint)((address[7] << 24) | (address[6] << 16) | (address[5] << 8) | (address[4]));

                    ipAddresses[i] = new IPAddress((long)ipAddr);
                }
            }

            ipHostEntry.hostName = canonicalName;
            ipHostEntry.addressList = ipAddresses;

            return ipHostEntry;
        }
Esempio n. 22
0
        public override EndPoint Create(SocketAddress SockAddr)
        {
            if (SockAddr == null ||
                SockAddr.Family != AF_HYPERV ||
                SockAddr.Size != 34)
            {
                return null;
            }

            HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(SockAddr.Family, Guid.Empty, Guid.Empty);

            string sockAddress = SockAddr.ToString();

            endpoint.VmId = new Guid(sockAddress.Substring(4, 16));
            endpoint.ServiceId = new Guid(sockAddress.Substring(20, 16));

            return endpoint;
        }
Esempio n. 23
0
        public void TestCreate ()
        {
            const string socketFile = "test";
            // mangledSocketFile simulates the socket file name with a null
            // terminator and junk after the null terminator. This can be present
            // in a SocketAddress when marshaled from native code.
            const string mangledSocketFile = socketFile + "\0junk";

            var bytes = Encoding.Default.GetBytes (mangledSocketFile);
            var socketAddress = new SocketAddress (AddressFamily.Unix, bytes.Length + 2);
            for (int i = 0; i < bytes.Length; i++) {
                socketAddress [i + 2] = bytes [i];
            }
            var dummyEndPoint = new UnixEndPoint (socketFile);

            // testing that the Create() method strips off the null terminator and the junk
            var endPoint = (UnixEndPoint)dummyEndPoint.Create (socketAddress);
            Assert.AreEqual (socketFile, endPoint.Filename, "#A01");
        }
Esempio n. 24
0
        public override SocketAddress Serialize()
        {
            // create a new SocketAddress
            //
            SocketAddress socketAddress = new SocketAddress(AddressFamily.InterNetwork, SocketAddress.IPv4AddressSize);
            byte[] buffer = socketAddress.m_Buffer;
            //
            // populate it
            //
            buffer[2] = unchecked((byte)(this.m_Port >> 8));
            buffer[3] = unchecked((byte)(this.m_Port));

            buffer[4] = unchecked((byte)(this.m_Address.m_Address));
            buffer[5] = unchecked((byte)(this.m_Address.m_Address >> 8));
            buffer[6] = unchecked((byte)(this.m_Address.m_Address >> 16));
            buffer[7] = unchecked((byte)(this.m_Address.m_Address >> 24));

            return socketAddress;
        }
 internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, System.Net.SocketAddress socketAddress, bool pinSocketAddress)
 {
     this.m_SocketAddress = socketAddress;
     if (pinSocketAddress && (this.m_SocketAddress != null))
     {
         object[] objectsToPin = null;
         objectsToPin    = new object[2];
         objectsToPin[0] = buffer;
         this.m_SocketAddress.CopyAddressSizeIntoBuffer();
         objectsToPin[1] = this.m_SocketAddress.m_Buffer;
         base.SetUnmanagedStructures(objectsToPin);
     }
     else
     {
         base.SetUnmanagedStructures(buffer);
     }
     this.m_SingleBuffer.Length  = size;
     this.m_SingleBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);
 }
Esempio n. 26
0
        internal unsafe void SetUnmanagedStructures(byte[] buffer, int offset, int size, System.Net.SocketAddress socketAddress, SocketFlags socketFlags)
        {
            bool flag  = ((Socket)base.AsyncObject).AddressFamily == AddressFamily.InterNetwork;
            bool flag2 = ((Socket)base.AsyncObject).AddressFamily == AddressFamily.InterNetworkV6;

            this.m_MessageBuffer  = new byte[s_WSAMsgSize];
            this.m_WSABufferArray = new byte[s_WSABufferSize];
            if (flag)
            {
                this.m_ControlBuffer = new byte[s_ControlDataSize];
            }
            else if (flag2)
            {
                this.m_ControlBuffer = new byte[s_ControlDataIPv6Size];
            }
            object[] objectsToPin = new object[(this.m_ControlBuffer != null) ? 5 : 4];
            objectsToPin[0]      = buffer;
            objectsToPin[1]      = this.m_MessageBuffer;
            objectsToPin[2]      = this.m_WSABufferArray;
            this.m_SocketAddress = socketAddress;
            this.m_SocketAddress.CopyAddressSizeIntoBuffer();
            objectsToPin[3] = this.m_SocketAddress.m_Buffer;
            if (this.m_ControlBuffer != null)
            {
                objectsToPin[4] = this.m_ControlBuffer;
            }
            base.SetUnmanagedStructures(objectsToPin);
            this.m_WSABuffer             = (WSABuffer *)Marshal.UnsafeAddrOfPinnedArrayElement(this.m_WSABufferArray, 0);
            this.m_WSABuffer.Length      = size;
            this.m_WSABuffer.Pointer     = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);
            this.m_Message               = (UnsafeNclNativeMethods.OSSOCK.WSAMsg *)Marshal.UnsafeAddrOfPinnedArrayElement(this.m_MessageBuffer, 0);
            this.m_Message.socketAddress = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_SocketAddress.m_Buffer, 0);
            this.m_Message.addressLength = (uint)this.m_SocketAddress.Size;
            this.m_Message.buffers       = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_WSABufferArray, 0);
            this.m_Message.count         = 1;
            if (this.m_ControlBuffer != null)
            {
                this.m_Message.controlBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_ControlBuffer, 0);
                this.m_Message.controlBuffer.Length  = this.m_ControlBuffer.Length;
            }
            this.m_Message.flags = socketFlags;
        }
 internal static IPAddressCollection ToAddressCollection(IntPtr ptr, IPVersion versionSupported)
 {
     IPAddressCollection addresss = new IPAddressCollection();
     if (ptr != IntPtr.Zero)
     {
         IPEndPoint point;
         IpAdapterAddress address = (IpAdapterAddress) Marshal.PtrToStructure(ptr, typeof(IpAdapterAddress));
         AddressFamily family = (address.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
         SocketAddress socketAddress = new SocketAddress(family, address.address.addressLength);
         Marshal.Copy(address.address.address, socketAddress.m_Buffer, 0, address.address.addressLength);
         if (family == AddressFamily.InterNetwork)
         {
             point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress);
         }
         else
         {
             point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress);
         }
         addresss.InternalAdd(point.Address);
         while (address.next != IntPtr.Zero)
         {
             address = (IpAdapterAddress) Marshal.PtrToStructure(address.next, typeof(IpAdapterAddress));
             family = (address.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
             if (((family == AddressFamily.InterNetwork) && ((versionSupported & IPVersion.IPv4) > IPVersion.None)) || ((family == AddressFamily.InterNetworkV6) && ((versionSupported & IPVersion.IPv6) > IPVersion.None)))
             {
                 socketAddress = new SocketAddress(family, address.address.addressLength);
                 Marshal.Copy(address.address.address, socketAddress.m_Buffer, 0, address.address.addressLength);
                 if (family == AddressFamily.InterNetwork)
                 {
                     point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress);
                 }
                 else
                 {
                     point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress);
                 }
                 addresss.InternalAdd(point.Address);
             }
         }
     }
     return addresss;
 }
Esempio n. 28
0
        //
        // socketAddress must always be the result of remoteEP.Serialize()
        //
        private void CheckCacheRemote(SocketAddress socketAddress, EndPoint remoteEP, bool isOverwrite) {
            // We remember the first peer we have communicated with
            if (m_PermittedRemoteAddress != null && m_PermittedRemoteAddress.Equals(socketAddress)) {
                return;
            }
            //
            // for now SocketPermission supports only IPEndPoint
            //
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                //
                // cast the EndPoint to IPEndPoint
                //
                IPEndPoint remoteIPEndPoint = (IPEndPoint)remoteEP;
                //
                // create the permissions the user would need for the call
                //
                SocketPermission socketPermission
                    = new SocketPermission(
                        NetworkAccess.Connect,
                        Transport,
                        remoteIPEndPoint.Address.ToString(),
                        remoteIPEndPoint.Port);
                //
                // demand for them
                //
                socketPermission.Demand();
            }
            else {
                //
                // for V1 we will demand permission to run UnmanagedCode for
                // an EndPoint that is not an IPEndPoint until we figure out how these fit
                // into the whole picture of SocketPermission
                //

                (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
            }
            //cache only the first peer we communicated with
            if (m_PermittedRemoteAddress == null || isOverwrite) {
                m_PermittedRemoteAddress = socketAddress;
            }
        }
Esempio n. 29
0
		public override EndPoint Create (SocketAddress socketAddress)
		{
			/*
			 * Should also check this
			 *
			int addr = (int) AddressFamily.Unix;
			if (socketAddress [0] != (addr & 0xFF))
				throw new ArgumentException ("socketAddress is not a unix socket address.");

			if (socketAddress [1] != ((addr & 0xFF00) >> 8))
				throw new ArgumentException ("socketAddress is not a unix socket address.");
			 */

			byte [] bytes = new byte [socketAddress.Size - 2];
			for (int i = 0; i < bytes.Length; i++) {
				bytes [i] = socketAddress [i + 2];
			}

			string name = Encoding.Default.GetString (bytes);
			return new UnixEndPoint (name);
		}
	// Create an end point from a socket address.
	public override EndPoint Create(SocketAddress sockaddr)
			{
				// Extract the device ID [2..5] from the socket address.
				byte[] deviceID = new byte [4];
				deviceID[0] = sockaddr[2];
				deviceID[1] = sockaddr[3];
				deviceID[2] = sockaddr[4];
				deviceID[3] = sockaddr[5];

				// Extract the service name [6..] from the socket address.
				int posn = 6;
				StringBuilder builder = new StringBuilder();
				while(posn < sockaddr.Size && sockaddr[posn] != 0)
				{
					builder.Append((char)(sockaddr[posn]));
					++posn;
				}

				// Build and return the new end point.
				return new IrDAEndPoint(deviceID, builder.ToString());
			}
Esempio n. 31
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 override EndPoint Create(SocketAddress socketAddress) {
     int index;
     if (socketAddress == null) {
         throw new ArgumentNullException("socketAddress");
     }
     if (socketAddress[0] != 0x20) {
         return base.Create(socketAddress);
     }
     byte[] address = new byte[6];
     for (index = 0; index < 6; index++) {
         address[index] = socketAddress[m_addressoffset + index];
     }
     byte[] b = new byte[0x10];
     for (index = 0; index < 0x10; index++) {
         b[index] = socketAddress[m_serviceoffset + index];
     }
     byte[] buffer3 = new byte[4];
     for (index = 0; index < 4; index++) {
         buffer3[index] = socketAddress[m_portoffset + index];
     }
     return new BluetoothEndPoint(new BluetoothAddress(address), new Guid(b), BitConverter.ToInt32(buffer3, 0));
 }
Esempio n. 33
0
        public static EndPoint Create(this EndPoint thisObj, Internals.SocketAddress socketAddress)
        {
            AddressFamily family = socketAddress.Family;

            if (family != thisObj.AddressFamily)
            {
                throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, family.ToString(), thisObj.GetType().FullName, thisObj.AddressFamily.ToString()), nameof(socketAddress));
            }

            if (family == AddressFamily.InterNetwork || family == AddressFamily.InterNetworkV6)
            {
                if (socketAddress.Size < 8)
                {
                    throw new ArgumentException(SR.Format(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName, thisObj.GetType().FullName), nameof(socketAddress));
                }

                return(socketAddress.GetIPEndPoint());
            }

            System.Net.SocketAddress address = GetNetSocketAddress(socketAddress);
            return(thisObj.Create(address));
        }
 internal static MulticastIPAddressInformationCollection ToAddressInformationCollection(IntPtr ptr)
 {
     MulticastIPAddressInformationCollection informations = new MulticastIPAddressInformationCollection();
     if (ptr != IntPtr.Zero)
     {
         IPEndPoint point;
         IpAdapterAddress adapterAddress = (IpAdapterAddress) Marshal.PtrToStructure(ptr, typeof(IpAdapterAddress));
         AddressFamily family = (adapterAddress.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
         SocketAddress socketAddress = new SocketAddress(family, adapterAddress.address.addressLength);
         Marshal.Copy(adapterAddress.address.address, socketAddress.m_Buffer, 0, adapterAddress.address.addressLength);
         if (family == AddressFamily.InterNetwork)
         {
             point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress);
         }
         else
         {
             point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress);
         }
         informations.InternalAdd(new SystemMulticastIPAddressInformation(adapterAddress, point.Address));
         while (adapterAddress.next != IntPtr.Zero)
         {
             adapterAddress = (IpAdapterAddress) Marshal.PtrToStructure(adapterAddress.next, typeof(IpAdapterAddress));
             family = (adapterAddress.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
             socketAddress = new SocketAddress(family, adapterAddress.address.addressLength);
             Marshal.Copy(adapterAddress.address.address, socketAddress.m_Buffer, 0, adapterAddress.address.addressLength);
             if (family == AddressFamily.InterNetwork)
             {
                 point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress);
             }
             else
             {
                 point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress);
             }
             informations.InternalAdd(new SystemMulticastIPAddressInformation(adapterAddress, point.Address));
         }
     }
     return informations;
 }
        //
        // SetUnmanagedStructures -
        // Fills in Overlapped Structures used in an Async Overlapped Winsock call
        //   these calls are outside the runtime and are unmanaged code, so we need
        //   to prepare specific structures and ints that lie in unmanaged memory
        //   since the Overlapped calls can be Async
        //

        internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, bool pinSocketAddress)
        {
            //
            // Fill in Buffer Array structure that will be used for our send/recv Buffer
            //
            m_SocketAddress = socketAddress;
            if (pinSocketAddress && m_SocketAddress != null)
            {
                object[]  objectsToPin = null;
                objectsToPin = new object[2];
                objectsToPin[0] = buffer;

                m_SocketAddress.CopyAddressSizeIntoBuffer();
                objectsToPin[1] = m_SocketAddress.m_Buffer;

                base.SetUnmanagedStructures(objectsToPin);
            } else {
                base.SetUnmanagedStructures(buffer);
            }

            m_SingleBuffer.Length = size;
            m_SingleBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);
        }
 public virtual EndPoint Create(SocketAddress address)
 {
     throw NotImplemented();
 }
Esempio n. 37
0
        // bytes 2 and 3 store the port, the rest
        // stores the address
        public override EndPoint Create(SocketAddress socketAddress)
        {
            if (socketAddress == null)
            {
                throw new ArgumentNullException("socketAddress");
            }

            if (socketAddress.Family != AddressFamily)
            {
                throw new ArgumentException("The IPEndPoint was created using " + AddressFamily +
                                            " AddressFamily but SocketAddress contains " + socketAddress.Family +
                                            " instead, please use the same type.");
            }

            SocketAddress sockaddr = socketAddress;
            int           size     = sockaddr.Size;
            AddressFamily family   = sockaddr.Family;
            int           port;

            IPEndPoint ipe = null;

            switch (family)
            {
            case AddressFamily.InterNetwork:
                if (size < 8)
                {
                    return(null);
                }

                port = (((int)sockaddr[2]) << 8) + (int)sockaddr[3];
                long address = (((long)sockaddr[7]) << 24) +
                               (((long)sockaddr[6]) << 16) +
                               (((long)sockaddr[5]) << 8) +
                               (long)sockaddr[4];

                ipe = new IPEndPoint(address, port);
                break;

#if NET_1_1
            case AddressFamily.InterNetworkV6:
                if (size < 28)
                {
                    return(null);
                }

                port = (((int)sockaddr[2]) << 8) + (int)sockaddr[3];

                /// maybe flowid ?

                /*
                 * int unknown	= (int)sockaddr[4] +
                 *  (((int)sockaddr[5])<<8) +
                 *  (((int)sockaddr[6])<<16) +
                 *  (((int)sockaddr[7])<<24);
                 */

                int scopeId = (int)sockaddr[24] +
                              (((int)sockaddr[25]) << 8) +
                              (((int)sockaddr[26]) << 16) +
                              (((int)sockaddr[27]) << 24);

                ushort[] addressData = new ushort[8];
                for (int i = 0; i < 8; i++)
                {
                    addressData[i] = (ushort)((sockaddr[8 + i * 2] << 8) + sockaddr[8 + i * 2 + 1]);
                }

                ipe = new IPEndPoint(new IPAddress(addressData, scopeId), port);
                break;
#endif
            default:
                return(null);
            }

            return(ipe);
        }
Esempio n. 38
0
        public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
        {
            //
            // Use SocketException here to show operation not supported
            // if, by some nefarious means, this method is called on an
            // unsupported platform.
            //
            SafeFreeAddrInfo root = null;
            var    addresses      = new List <IPAddress>();
            string canonicalname  = null;

            AddressInfo hints = new AddressInfo();

            hints.ai_flags  = AddressInfoHints.AI_CANONNAME;
            hints.ai_family = AddressFamily.Unspecified;   // gets all address families

            nativeErrorCode = 0;

            //
            // Use try / finally so we always get a shot at freeaddrinfo
            //
            try
            {
                SocketError errorCode = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out root);
                if (errorCode != SocketError.Success)
                { // Should not throw, return mostly blank hostentry
                    hostinfo = NameResolutionUtilities.GetUnresolvedAnswer(name);
                    return(errorCode);
                }

                AddressInfo *pAddressInfo = (AddressInfo *)root.DangerousGetHandle();
                //
                // Process the results
                //
                while (pAddressInfo != null)
                {
                    SocketAddress sockaddr;
                    //
                    // Retrieve the canonical name for the host - only appears in the first AddressInfo
                    // entry in the returned array.
                    //
                    if (canonicalname == null && pAddressInfo->ai_canonname != null)
                    {
                        canonicalname = Marshal.PtrToStringUni((IntPtr)pAddressInfo->ai_canonname);
                    }
                    //
                    // Only process IPv4 or IPv6 Addresses. Note that it's unlikely that we'll
                    // ever get any other address families, but better to be safe than sorry.
                    // We also filter based on whether IPv6 is supported on the current
                    // platform / machine.
                    //
                    if ((pAddressInfo->ai_family == AddressFamily.InterNetwork) || // Never filter v4
                        (pAddressInfo->ai_family == AddressFamily.InterNetworkV6 && SocketProtocolSupportPal.OSSupportsIPv6))
                    {
                        sockaddr = new SocketAddress(pAddressInfo->ai_family, pAddressInfo->ai_addrlen);
                        //
                        // Push address data into the socket address buffer
                        //
                        for (int d = 0; d < pAddressInfo->ai_addrlen; d++)
                        {
                            sockaddr[d] = *(pAddressInfo->ai_addr + d);
                        }
                        //
                        // NOTE: We need an IPAddress now, the only way to create it from a
                        //       SocketAddress is via IPEndPoint. This ought to be simpler.
                        //
                        if (pAddressInfo->ai_family == AddressFamily.InterNetwork)
                        {
                            addresses.Add(((IPEndPoint)IPEndPointStatics.Any.Create(sockaddr)).Address);
                        }
                        else
                        {
                            addresses.Add(((IPEndPoint)IPEndPointStatics.IPv6Any.Create(sockaddr)).Address);
                        }
                    }
                    //
                    // Next addressinfo entry
                    //
                    pAddressInfo = pAddressInfo->ai_next;
                }
            }
            finally
            {
                if (root != null)
                {
                    root.Dispose();
                }
            }

            //
            // Finally, put together the IPHostEntry
            //
            hostinfo = new IPHostEntry();

            hostinfo.HostName    = canonicalname != null ? canonicalname : name;
            hostinfo.Aliases     = Array.Empty <string>();
            hostinfo.AddressList = addresses.ToArray();

            return(SocketError.Success);
        }
Esempio n. 39
0
 /// <devdoc>
 ///    <para>
 ///       Creates an EndPoint instance from a SocketAddress structure.
 ///    </para>
 /// </devdoc>
 public virtual EndPoint Create(SocketAddress socketAddress)
 {
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
Esempio n. 40
0
 internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, System.Net.SocketAddress socketAddress, SocketFlags socketFlags, ref OverlappedCache overlappedCache)
 {
     base.SetupCache(ref overlappedCache);
     this.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);
 }