GetAddressBytes() публичный Метод

public GetAddressBytes ( ) : byte[]
Результат byte[]
Пример #1
1
        public static string GetNetworkAddressAsString(IPAddress address, IPAddress mask)
        {
            string netIP = ""; // Network address as string
            int networkLength = 0;

            if (null != mask)
            {
                for (int i = 0; i < 4; i++)
                {
                    byte ba = address.GetAddressBytes()[i];
                    byte bm = mask.GetAddressBytes()[i];

                    netIP += ba & bm;
                    if (i < 3) netIP += ".";
                    networkLength += 8 - (int)System.Math.Truncate(System.Math.Log(256 - bm, 2));
                }
                netIP += "/" + networkLength;
            }
            else
            {
                netIP = address.ToString() + "/32";
            }

            return netIP;
        }
 public sockaddr_in6(IPAddress address)
 {
     if (address.AddressFamily == AddressFamily.InterNetworkV6)
     {
         this.sin6_addr = address.GetAddressBytes();
         this.sin6_scope_id = (uint) address.ScopeId;
     }
     else
     {
         byte[] addressBytes = address.GetAddressBytes();
         this.sin6_addr = new byte[0x10];
         for (int i = 0; i < 10; i++)
         {
             this.sin6_addr[i] = 0;
         }
         this.sin6_addr[10] = 0xff;
         this.sin6_addr[11] = 0xff;
         for (int j = 12; j < 0x10; j++)
         {
             this.sin6_addr[j] = addressBytes[j - 12];
         }
         this.sin6_scope_id = 0;
     }
     this.sin6_family = 0x17;
     this.sin6_port = 0;
     this.sin6_flowinfo = 0;
 }
Пример #3
0
 public SocketAddress(IPAddress ipAddress)
   : this(ipAddress.AddressFamily, ipAddress.AddressFamily == AddressFamily.InterNetwork ? 16 : 28)
 {
   this.m_buffer[2] = (byte)0;
   this.m_buffer[3] = (byte)0;
   if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
   {
     this.m_buffer[4] = (byte)0;
     this.m_buffer[5] = (byte)0;
     this.m_buffer[6] = (byte)0;
     this.m_buffer[7] = (byte)0;
     long scopeId = ipAddress.ScopeId;
     this.m_buffer[24] = (byte)scopeId;
     this.m_buffer[25] = (byte)(scopeId >> 8);
     this.m_buffer[26] = (byte)(scopeId >> 16);
     this.m_buffer[27] = (byte)(scopeId >> 24);
     byte[] addressBytes = ipAddress.GetAddressBytes();
     for (int index = 0; index < addressBytes.Length; ++index)
       this.m_buffer[8 + index] = addressBytes[index];
   }
   else
   {
     System.Buffer.BlockCopy(ipAddress.GetAddressBytes(), 0, m_buffer, 4, 4);
   }
 }
Пример #4
0
        public WhoisTask(IPAddress ip)
        {
            StringBuilder host = new StringBuilder();
            switch (ip.AddressFamily)
            {
                // Turn the address into its in-addr.arpa form.
                case System.Net.Sockets.AddressFamily.InterNetwork:
                    foreach (byte octet in ip.GetAddressBytes().Reverse())
                    {
                        host.Append(octet.ToString() + ".");
                    }
                    host.Append("in-addr.arpa");
                    break;
                // Turn the address into its ip6.arpa form.
                case System.Net.Sockets.AddressFamily.InterNetworkV6:
                    foreach (byte octet in ip.GetAddressBytes().Reverse())
                    {
                        string hex = string.Format("{0:x2}", octet);
                        host.Append(string.Format("{0}.{1}.", hex[1], hex[0]));
                    }
                    host.Append("ip6.arpa");
                    break;

            }
            Host = host.ToString();
        }
Пример #5
0
        public unsafe void BlockSource(IPAddress groupAdress, IPAddress sourceAdress, uint interfaceIndex = 0)
        {
            if (groupAdress.AddressFamily != sourceAdress.AddressFamily)
                throw new ArgumentException("Address family must be the same");

            var adress = groupAdress.GetAddressBytes();
            var sourceadress = groupAdress.GetAddressBytes();

            if (groupAdress.AddressFamily == AddressFamily.InterNetwork)
            {
                ip_mreq_source value = new ip_mreq_source();
                value.imr_interface.s_b4 = (byte)interfaceIndex;
                fixed (byte* a = adress)
                    Unsafe.CopyBlock(value.imr_multiaddr.Address, a, (uint)adress.Length);

                fixed (byte* a = sourceadress)
                    Unsafe.CopyBlock(value.imr_multiaddr.Address, a, (uint)sourceadress.Length);

                if (SetSocketOption(IPPROTO_IP_SocketOptions.IP_BLOCK_SOURCE, (void*)&value, Marshal.SizeOf<ip_mreq_source>()) != 0)
                    WinSock.ThrowLastWSAError();
            }
            else if (groupAdress.AddressFamily == AddressFamily.InterNetworkV6)
            {

                //ipv6_mreq value = new ipv6_mreq();
                //value.ipv6mr_interface = interfaceIndex;
                //fixed (byte* a = adress)
                //    Unsafe.CopyBlock(value.ipv6mr_multiaddr.Address, a, (uint)adress.Length);

                //if (SetSocketOption(IPPROTO_IPV6_SocketOptions., (void*)&value, Marshal.SizeOf<ipv6_mreq>()) != 0)
                //    WinSock.ThrowLastWSAError();
            }
        }
Пример #6
0
 public static string FormatIp(IPAddress ipa)
 {
     string ipData = string.Empty;
     if (ipa.AddressFamily == AddressFamily.InterNetwork)
     {
         ipData = "IPv4";
         foreach (byte b in ipa.GetAddressBytes())
         {
             if (ipData[ipData.Length - 1] != ' ')
                 ipData += ".";
             ipData += string.Format("{0}", b);
         }
     }
     else
     {
         ipData = "IPv6";
         byte[] bytes = ipa.GetAddressBytes();
         for (int i = 0; i < bytes.Length; i = i + 2)
         {
             if (ipData[ipData.Length - 1] != ' ')
                 ipData += ":";
             byte b = bytes[i];
             ipData += string.Format("{0:X2}", b);
             b = bytes[i + 1];
             ipData += string.Format("{0:X2}", b);
         }
     }
     return ipData;
 }
 public static IPAddress CloneAddress(IPAddress source, bool maskScopeId)
 {
     if (maskScopeId || V4Address(source))
     {
         return new IPAddress(source.GetAddressBytes());
     }
     return new IPAddress(source.GetAddressBytes(), source.ScopeId);
 }
Пример #8
0
 private static long IPToLong(IPAddress address)
 {
     MemoryStream ms = new MemoryStream();
     ms.Write(address.GetAddressBytes(), 0, address.GetAddressBytes().Length);
     while (ms.Length < 8)
         ms.WriteByte(0);
     return System.BitConverter.ToInt64(ms.ToArray(), 0);
 }
Пример #9
0
        public InternetAddress(IPAddress address)
        {
            if (address == null || address.GetAddressBytes().Length != 4)
            {
                _address = null;
            }

            _address = address.GetAddressBytes();
        }
Пример #10
0
        public NetAddr(Services services, IPAddress address, UInt16 port)
        {
            this.services = services;
            this.address = address;
            this.port = port;

            if (address.GetAddressBytes().Length != 16)
                this.address = new IPAddress((new Byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF })
                    .Concat(address.GetAddressBytes()).ToArray());
        }
Пример #11
0
 public IPNetwork(IPAddress prefix, int prefixLength)
 {
     Prefix = prefix;
     PrefixLength = prefixLength;
     PrefixBytes = Prefix.GetAddressBytes();
     Mask = CreateMask();
 }
Пример #12
0
        public bool IsInRange(IPAddress address)
        {
            if (address.AddressFamily != addressFamily)
            {
                return false;
            }

            var addressBytes = address.GetAddressBytes();

            bool lowerBoundary = true, upperBoundary = true;

            for (var i = 0; i < lowerBytes.Length &&
                            (lowerBoundary || upperBoundary); i++)
            {
                if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) || (upperBoundary && addressBytes[i] > upperBytes[i]))
                {
                    return false;
                }

                lowerBoundary &= (addressBytes[i] == lowerBytes[i]);
                upperBoundary &= (addressBytes[i] == upperBytes[i]);
            }

            return true;
        }
        public static bool IsInRange(this IPAddress address, IPAddress start, IPAddress end)
        {
            AddressFamily addressFamily = start.AddressFamily;
            byte[] lowerBytes = start.GetAddressBytes();
            byte[] upperBytes = end.GetAddressBytes();

            if (address.AddressFamily != addressFamily)
            {
                return false;
            }

            byte[] addressBytes = address.GetAddressBytes();

            bool lowerBoundary = true, upperBoundary = true;

            for (int i = 0; i < lowerBytes.Length &&
                (lowerBoundary || upperBoundary); i++)
            {
                if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) ||
                    (upperBoundary && addressBytes[i] > upperBytes[i]))
                {
                    return false;
                }

                lowerBoundary &= (addressBytes[i] == lowerBytes[i]);
                upperBoundary &= (addressBytes[i] == upperBytes[i]);
            }

            return true;
        }
Пример #14
0
        public static IPAddress UintToIP(uint ipaddr, bool reverse = false, bool IsLittleEndian = true)
        {
            //fix endianess from network
            if (IsLittleEndian)
            {
                ipaddr = (
                    (ipaddr << 24) & 0xFF000000) +
                         ((ipaddr << 8) & 0x00FF0000) +
                         ((ipaddr >> 8) & 0x0000FF00) +
                         ((ipaddr >> 24) & 0x000000FF
                         );
            }
            else
            {
                ipaddr = (
                    ((ipaddr >> 24) & 0x000000FF +
                     ((ipaddr >> 8) & 0x0000FF00) +
                     ((ipaddr << 8) & 0x00FF0000) +
                     (ipaddr << 24) & 0xFF000000)
                    );
            }

            var result = new System.Net.IPAddress(ipaddr);

            if (reverse)
            {
                result = new IPAddress(result.GetAddressBytes().Reverse().ToArray());
            }
            return(result);
        }
Пример #15
0
        private int ProcessSHandshake(Protocol _p)
        {
            Handshake.SHandshake p = (Handshake.SHandshake)_p;
            if (DHContext.TryGetValue(p.Sender.SessionId, out var dhRandom))
            {
                Array.Reverse(p.Argument.dh_data);
                byte[] material = Handshake.Helper.computeDHKey(
                    Config.HandshakeOptions.DhGroup,
                    new BigInteger(p.Argument.dh_data),
                    dhRandom).ToByteArray();
                Array.Reverse(material);
                System.Net.IPAddress ipaddress =
                    ((IPEndPoint)p.Sender.Socket.RemoteEndPoint).Address;
                if (ipaddress.IsIPv4MappedToIPv6)
                {
                    ipaddress = ipaddress.MapToIPv4();
                }
                byte[] key = ipaddress.GetAddressBytes();
                logger.Debug("{0} remoteip={1}", p.Sender.SessionId, BitConverter.ToString(key));

                int    half    = material.Length / 2;
                byte[] hmacMd5 = Digest.HmacMd5(key, material, 0, half);
                p.Sender.SetOutputSecurityCodec(hmacMd5, p.Argument.c2sneedcompress);
                hmacMd5 = Digest.HmacMd5(key, material, half, material.Length - half);
                p.Sender.SetInputSecurityCodec(hmacMd5, p.Argument.s2cneedcompress);

                DHContext.TryRemove(p.Sender.SessionId, out var _);
                new Handshake.CHandshakeDone().Send(p.Sender);
                OnHandshakeDone(p.Sender);
                return(0);
            }
            throw new Exception("handshake lost context.");
        }
Пример #16
0
        public static uint  ReToNumIP(string ip)
        {
            if (ip == null || ip.Length < 1)
            {
                return(0);
            }

            uint IP = 0;

            byte[] addbyte = new byte[128];
            try
            {
                System.Net.IPAddress ipaddr = System.Net.IPAddress.Parse(ip);
                addbyte = ipaddr.GetAddressBytes();
                byte[] IPByte = new byte[4];
                IPByte[0] = addbyte[3];
                IPByte[1] = addbyte[2];
                IPByte[2] = addbyte[1];
                IPByte[3] = addbyte[0];
                IP        = System.BitConverter.ToUInt32(IPByte, 0);
            }
            catch (System.Exception e1)
            {
                Tools.WriteLog("ICS AdminPortal", e1.ToString(), System.Diagnostics.EventLogEntryType.Error);
                return(0);
            }
            return(IP);
        }
Пример #17
0
        public void Initial(System.Net.IPAddress startIP, System.Net.IPAddress endIP)
        {
            if (Helper.Compare(startIP, endIP) == 1)
            {
                var tempIp = endIP;
                endIP   = startIP;
                startIP = tempIp;
            }

            ltbxIPAddressesRange.DataSource = null;

            var IPAddressesRange  = new List <System.Net.IPAddress>();
            var startIPBytesArray = startIP.GetAddressBytes();
            var endIPBytesArray   = endIP.GetAddressBytes();

            Array.Reverse(startIPBytesArray);
            Array.Reverse(endIPBytesArray);

            _startIP = BitConverter.ToUInt32(startIPBytesArray, 0);
            _endIP   = BitConverter.ToUInt32(endIPBytesArray, 0);

            double pagesCount = ((double)_endIP + 1) / (double)_recordsPerPage;

            _totalPages = (int)(Math.Ceiling(pagesCount));

            _currentPage = _totalPages > 0 ? 1 : 0;

            if (_totalPages > 1)
            {
                EnableNavigation(true);
            }

            navigation.CurrentPage = _currentPage;
            navigation.TotalPages  = _totalPages;
        }
Пример #18
0
        private List <string> get_ip_list(string start_ip, string end_ip)
        {
            System.Net.IPAddress startIP = System.Net.IPAddress.Parse(start_ip);
            System.Net.IPAddress lastIP  = System.Net.IPAddress.Parse(end_ip);

            byte [] beginIP  = startIP.GetAddressBytes();
            byte [] endIP    = lastIP.GetAddressBytes();
            int     capacity = 1;

            for (int i = 0; i < 4; i++)
            {
                capacity *= endIP[i] - beginIP[i] + 1;
            }

            List <string> ips = new List <string>(capacity);

            for (int i0 = beginIP[0]; i0 <= endIP[0]; i0++)
            {
                for (int i1 = beginIP[1]; i1 <= endIP[1]; i1++)
                {
                    for (int i2 = beginIP[2]; i2 <= endIP[2]; i2++)
                    {
                        for (int i3 = beginIP[3]; i3 <= endIP[3]; i3++)
                        {
                            ips.Add(new IPAddress(new byte[] { (byte)i0, (byte)i1, (byte)i2, (byte)i3 }).ToString());
                        }
                    }
                }
            }

            return(ips);
        }
Пример #19
0
 public static OSD FromIP(IPAddress address)
 {
     if (address != null && address != IPAddress.Any)
         return OSD.FromBinary(address.GetAddressBytes());
     else
         return new OSD();
 }
Пример #20
0
        // get IPv6 pseudo-header (adapted from: http://www.winsocketdotnetworkprogramming.com/clientserversocketnetworkcommunication8f_3.html)
        public static byte[] GetPseudoHeader(IPAddress sourceIP, IPAddress destinationIP, int icmpv6Length, int nextHeader)
        {
            byte[] pseudoHeader, byteValue;
            int offset = 0, payLoadLength;

            // now build the pseudo header
            pseudoHeader = new byte[40];

            byteValue = sourceIP.GetAddressBytes();
            Array.Copy(byteValue, 0, pseudoHeader, offset, byteValue.Length);
            offset += byteValue.Length;

            byteValue = destinationIP.GetAddressBytes();
            Array.Copy(byteValue, 0, pseudoHeader, offset, byteValue.Length);
            offset += byteValue.Length;

            // Packet total length
            payLoadLength = IPAddress.HostToNetworkOrder(4 + icmpv6Length);

            byteValue = BitConverter.GetBytes(payLoadLength);
            Array.Copy(byteValue, 0, pseudoHeader, offset, byteValue.Length);
            offset += byteValue.Length;

            // 3 bytes of zero padding
            pseudoHeader[offset++] = (byte)0;
            pseudoHeader[offset++] = (byte)0;
            pseudoHeader[offset++] = (byte)0;
            pseudoHeader[offset++] = (byte)nextHeader;

            return pseudoHeader;
        }
Пример #21
0
		public static IPAddress GetMatchingLocalIP(IPAddress clientAddr)
		{
			if (clientAddr.Equals(IPAddress.Any) ||
				clientAddr.Equals(IPAddress.Loopback))
			{
				return IPAddress.Loopback;
			}

			var clientBytes = clientAddr.GetAddressBytes();

			// find an address that matches the most significant n-1 bytes of the address of the connecting client
			foreach (var addr in CachedHostEntry.AddressList)
			{
				var bytes = addr.GetAddressBytes();
				if (bytes.Length != clientBytes.Length) continue;

				var match = true;
				for (var i = bytes.Length-2; i >= 0; i--)
				{
					if (bytes[i] != clientBytes[i])
					{
						match = false;
						break;
					}
				}
				if (match) return addr;
			}
			return null;
		}
        public static unsafe IPHostEntry GetHostByAddr(IPAddress addr)
        {
            // TODO #2891: Optimize this (or decide if this legacy code can be removed):
            byte[] addressBytes = addr.GetAddressBytes();
            var address = new Interop.libc.in_addr { s_addr = unchecked((uint)BitConverter.ToInt32(addressBytes, 0)) };

            int bufferSize = 512;
            byte* stackBuffer = stackalloc byte[bufferSize];

            var hostent = default(Interop.libc.hostent);
            var result = (Interop.libc.hostent*)null;
            if (TryGetHostByAddr(address, stackBuffer, bufferSize, &hostent, &result))
            {
                return CreateHostEntry(result);
            }

            for (; ;)
            {
                bufferSize *= 2;
                fixed (byte* heapBuffer = new byte[bufferSize])
                {
                    if (TryGetHostByAddr(address, heapBuffer, bufferSize, &hostent, &result))
                    {
                        return CreateHostEntry(result);
                    }
                }
            }
        }
Пример #23
0
		public void Initialize(Nic targetNic, IPAddress from = null, IPAddress to = null)
		{
			if (from == null)
				from = targetNic.Ip.V4.PrimaryUnicast.Network.FirstAddress;
			if (to == null)
				to = targetNic.Ip.V4.PrimaryUnicast.Network.LastAddress;

			uint firstUint = BitConverter.ToUInt32(from.GetAddressBytes().Reverse().ToArray(), 0);
			uint lastUint = BitConverter.ToUInt32(to.GetAddressBytes().Reverse().ToArray(), 0);

			//for (uint i = firstUint; i <= lastUint; i++)
			for (uint i = firstUint; i <= lastUint; i++)
			{
				var ipAddress = new IPAddress(BitConverter.GetBytes(i).Reverse().ToArray());
				var hostScan = new HostScan(ipAddress, targetNic.Ip.V4.PrimaryUnicast.Address);

				hostScan.Options = Options.HostScanOptions;
				hostScan.Options.Dns.DnsServer = targetNic.Raw.IpProperties.DnsAddresses.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);

				hostScan.State.Online += HostOnline;
				hostScan.State.Completed += HostScanCompleted;
				_scans.Add(hostScan);
			}

			Results.SetTotalScans((ushort) Scans.Count);
			Results.SetLocalNic(targetNic);
		}
Пример #24
0
		public void Initialize(Nic targetNic, IPAddress from = null, IPAddress to = null)
		{
			if (from == null)
				from = targetNic.Ip.V4.PrimaryUnicast.Network.FirstAddress;
			if (to == null)
				to = targetNic.Ip.V4.PrimaryUnicast.Network.LastAddress;

			uint firstUint = BitConverter.ToUInt32(from.GetAddressBytes().Reverse().ToArray(), 0);
			uint lastUint = BitConverter.ToUInt32(to.GetAddressBytes().Reverse().ToArray(), 0);

			//for (uint i = firstUint; i <= lastUint; i++)
			for (uint i = firstUint; i <= lastUint; i++)
			{
				var ipAddress = new IPAddress(BitConverter.GetBytes(i).Reverse().ToArray());
				var observer = new HostObserver(ipAddress, targetNic.Ip.V4.PrimaryUnicast.Address);

				observer.Options = Options.HostObserver;
				//hostChangeDetector.Options.Dns.DnsServer = targetNic.Raw.IpProperties.DnsAddresses.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);

				observer.State.ObserverSucceeded += ObserverSucceeded;
				observer.State.Activated += ObserverActivated;
				observer.State.Deactivated += ObserverDeactivated;

				_detectors.Add(observer);
			}

			Results.SetLocalNic(targetNic);
		}
Пример #25
0
        public POIBroadcast()
        {
            //Find current broadcast address
            broadCastAddr = IPAddress.Parse("192.168.1.255");
            IPAddress[] localAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in localAddresses)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {

                    //Find local address
                    localAddr = ip;
                    Console.WriteLine(ip.ToString());

                    //Find broadcast address
                    byte[] bcBytes = IPAddress.Broadcast.GetAddressBytes();
                    Array.Copy(localAddr.GetAddressBytes(), bcBytes, 3);
                    broadCastAddr = new IPAddress(bcBytes);
                    Console.WriteLine(broadCastAddr.ToString());
                }
            }

            //Initialize a broadcast channel using UDP
            broadCastChannel = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            broadCastChannel.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
        }
Пример #26
0
        public void ApplyServerHostnamePatch(IPAddress ipAddress)
        {
            if (ipAddress == null)
                throw new ArgumentNullException("ipAddress");

            ApplyServerHostnamePatch(ipAddress.GetAddressBytes());
        }
Пример #27
0
        public bool IsInRange(IPAddress address)
        {
            // Some people just have to be like that...
            if (address.AddressFamily != Family || address.GetLength() != LowerBoundary.Length)
                return false;

            var bytes = address.GetAddressBytes();

            var lowerBoundary = true;
            var upperBoundary = true;

            for (var i = 0; i < LowerBoundary.Length && (lowerBoundary || upperBoundary); i++)
            {
                var currentByte = bytes[i];
                var lowerByte = LowerBoundary[i];
                var upperByte = UpperBoundary[i];

                if ((lowerBoundary && currentByte < lowerByte) || (upperBoundary && currentByte > upperByte))
                    return false;

                lowerBoundary &= currentByte == lowerByte;
                upperBoundary &= currentByte == upperByte;
            }

            return true;
        }
Пример #28
0
        public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
        {
            var ipAdressBytes = address.GetAddressBytes();
            var subnetMaskBytes = subnetMask.GetAddressBytes();

            return new IPAddress(GetNetworkAddressBytes(ipAdressBytes, subnetMaskBytes));
        }
Пример #29
0
        public static bool CompareAddresses(Net.IPAddress a, Net.IPAddress b)
        {
            bool res = true;

            if ((a == null) && (b == null))
            {
                return(true);
            }
            if ((a == null) || (b == null))
            {
                return(false);
            }
            if (a.AddressFamily != b.AddressFamily)
            {
                return(false);
            }
            if (a.AddressFamily == Net.Sockets.AddressFamily.InterNetworkV6)
            {
                //IPAddress.Equals works wrong for ipv6 if address has different scope id
                byte[] bytesA = a.GetAddressBytes();
                byte[] bytesB = b.GetAddressBytes();
                for (int i = 0; i < bytesA.Length; i++)
                {
                    if (bytesA[i] != bytesB[i])
                    {
                        return(false);
                    }
                }
            }
            else
            {
                res = IPAddress.Equals(a, b);
            }
            return(res);
        }
Пример #30
0
 public static IPAddress GetLocalAddressFromRadioAddress(IPAddress radioAddress, int iIgnoreBytes)
 {
     NetworkInterface[] intfList = GetAvailableInterfaces();
     byte[] ipBytes = radioAddress.GetAddressBytes();
     if (ipBytes == null)
         return null;
     if (intfList == null || intfList.Length <= 0)
         return null;
     foreach (NetworkInterface ni in intfList)
     {
         IPInterfaceProperties ipProps = ni.GetIPProperties();
         foreach (UnicastIPAddressInformation uip in ipProps.UnicastAddresses)
         {
             byte[] uipByes = uip.Address.GetAddressBytes();
             if (uipByes == null)
                 continue;
             if (uipByes.Length == ipBytes.Length)
             {
                 bool b = true;
                 for (int i = 0; i < uipByes.Length - iIgnoreBytes; i++)
                 {
                     b &= (uipByes[i] == ipBytes[i]);
                 }
                 if (b)
                 {
                     return uip.Address;
                 }
             }
         }
     }
     return null;
 }
Пример #31
0
        private static IPAddress ParseIPv6AddressScope(Uri uri, IPAddress ipWithoutScope)
        {
            // Sometimes this can be escaped, sometimes not
            var idnHost = WebUtility.UrlDecode(uri.DnsSafeHost); // IdnHost is preferred in .NET 4.6
            var hostWithScopeParts = idnHost.Split(new[] { '%' }, 2);

            // Did they provide a scope?
            IPAddress ipWithScope;
            if (hostWithScopeParts.Length > 1)
            {
                var scopeName = hostWithScopeParts[1];

                // Just in case Syncthing ever starts returning proper scope IDs...
                long scopeId;
                if (!Int64.TryParse(scopeName, out scopeId))
                {

                    var scopeLevel = ipWithoutScope.IsIPv6SiteLocal ? ScopeLevel.Site : ScopeLevel.Interface;
                    // I've seen Go produce ID and Name
                    var network = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(x => x.Id == scopeName || x.Name == scopeName);

                    if (network == null)
                        throw new FormatException($"Unable to find an interface with name {scopeName}");

                    scopeId = network.GetIPProperties().GetIPv6Properties().GetScopeId(scopeLevel);
                }
                ipWithScope = new IPAddress(ipWithoutScope.GetAddressBytes(), scopeId);
            }
            else
            {
                ipWithScope = ipWithoutScope;
            }

            return ipWithScope;
        }
Пример #32
0
		public static IObservable<UdpReceiveResult> CreateListener(IPAddress remoteAddress, int port)
		{
			if (remoteAddress == null) throw new ArgumentNullException(nameof(remoteAddress));
			if (port < 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port), port, null);

			IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

			var remoteIPBytes = remoteAddress.GetAddressBytes();
			var localAddress =
				host.AddressList.FirstOrDefault(ip =>
				ip.AddressFamily == remoteAddress.AddressFamily
				&& ip.GetAddressBytes().Take(3).SequenceEqual(remoteIPBytes.Take(3)));

			if (localAddress == null)
				throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Net_NoInterfaceInSameNetwork, remoteAddress, port));

			var localEndPoint = new IPEndPoint(localAddress, port);
			var remoteEndPoint = new IPEndPoint(remoteAddress, port);

			return Observable.Using(
				() =>
				{
					var client = new UdpClient { ExclusiveAddressUse = false };
					client.Client.Bind(localEndPoint);
					client.Connect(remoteEndPoint.Address, 0);
					return client;
				},
				client => Observable.While(() => client.Client.Connected, Observable.FromAsync(client.ReceiveAsync)));
		}
Пример #33
0
 public long ip2long(String ip)
 {
     System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(ip);
     byte[] bytes = ipaddress.GetAddressBytes();
     Array.Reverse(bytes);
     return(BitConverter.ToUInt32(bytes, 0));
 }
Пример #34
0
        public static bool NetAddressIncludesIPAddress(string netaddress, IPAddress target)
        {
            int slash = netaddress.IndexOf('/');
            int bits = Int32.Parse(netaddress.Substring(slash + 1));
            IPAddress net = IPAddress.Parse(netaddress.Substring(0, slash));
            if (net.AddressFamily != target.AddressFamily)
                return false;

            byte[] bnet = net.GetAddressBytes();
            byte[] btarget = target.GetAddressBytes();
            Debug.Assert(bnet.Length == btarget.Length);

            for (int i = 0; i < bnet.Length; i++) {
                byte b1 = bnet[i];
                byte b2 = btarget[i];
                if (bits <= 0)
                    return true;
                else if (bits >= 8) {
                    if (b1 != b2)
                        return false;
                }
                else {
                    b1 >>= (8 - bits);
                    b2 >>= (8 - bits);
                    if (b1 != b2)
                        return false;
                }
                bits -= 8;
            }
            return true;
        }
        private static IResourceRecord Create(Domain domain, IPAddress ip, TimeSpan ttl)
        {
            byte[] data = ip.GetAddressBytes();
            RecordType type = data.Length == 4 ? RecordType.A : RecordType.AAAA;

            return new ResourceRecord(domain, data, type, RecordClass.IN, ttl);
        }
Пример #36
0
        public void UpdateAccountValues(UInt64 accId, UInt32 oneTimeKey, UInt32 sessId1, UInt32 sessId2, IPAddress ipa)
        {
            try
            {
                var off = ipa.AddressFamily == AddressFamily.InterNetworkV6 ? 12 : 0;
                var lastIp = String.Format("{0}.{1}.{2}.{3}", ipa.GetAddressBytes()[off + 0], ipa.GetAddressBytes()[off + 1], ipa.GetAddressBytes()[off + 2], ipa.GetAddressBytes()[off + 3]);

                lock (DataAccess.DatabaseAccess)
                    using (var comm = DataAccess.DatabaseAccess.CreateCommand(String.Format("UPDATE `account` SET `OneTimeKey` = {0}, `SessionId1` = {1}, `SessionId2` = {2}, `LastIP` = '{3}' WHERE `Id` = {4}", oneTimeKey, sessId1, sessId2, lastIp, accId)))
                        comm.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Logger.WriteLog("Exception in UpdateAccountValues! Exception: {0}", LogType.Error, e);
            }
        }
Пример #37
0
 public int addIPRangeToPool(IPAddress start, IPAddress end, IPAddress netmask)
 {
     byte[] data;
     data = start.GetAddressBytes();
     UInt32 range_start = EndianBitConverter.Big.ToUInt32( data, 0 );
     data = end.GetAddressBytes();
     UInt32 range_stop = EndianBitConverter.Big.ToUInt32(data, 0);
     int count = 0;
     if (range_start <= range_stop)
     {
         IPAddress ip;
         lock (ip_pool)
         {
             for (UInt32 i = range_start; i <= range_stop; i++)
             {
                 ip = new IPAddress(EndianBitConverter.Big.GetBytes(i));
                 if (!hasNattedIP(ip))
                 {
                     ip_pool.Add(new xbs_nat_entry(null, null, ip, netmask));
                     count++;
                 }
             }
         }
         xbs_messages.addDebugMessage("% NAT IP pool filled with " + count + " ip addresses. Total count of IPs in pool: " + ip_pool.Count, xbs_message_sender.NAT);
     }
     return count;
 }
Пример #38
0
        /// <summary>
        /// Checks if the given IP falls into the specified range
        /// </summary>
        /// <param name="target">The IP to check</param>
        /// <returns>True if it is inside the range, otherwise false</returns>
        public override bool Matches(System.Net.IPAddress target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            byte[] addressBytes = target.GetAddressBytes();

            bool lowerBoundary = true, upperBoundary = true;

            for (int i = 0; i < StartAddress.GetAddressBytes().Length&&
                 (lowerBoundary || upperBoundary); i++)
            {
                if ((lowerBoundary && addressBytes[i] < StartAddress.GetAddressBytes()[i]) ||
                    (upperBoundary && addressBytes[i] > EndAddress.GetAddressBytes()[i]))
                {
                    return(false);
                }

                lowerBoundary &= (addressBytes[i] == StartAddress.GetAddressBytes()[i]);
                upperBoundary &= (addressBytes[i] == EndAddress.GetAddressBytes()[i]);
            }

            return(true);
        }
Пример #39
0
        public static string GetMacAddressByIP(System.Net.IPAddress ipAddress)
        {
            byte[] macBytes = new byte[6];
            int    length   = 6;

            SendARP(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0), 0, macBytes, ref length);
            return(BitConverter.ToString(macBytes, 0, 6));
        }
Пример #40
0
        private uint ReturnFirtsOctet(string ipAddress)
        {
            System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ipAddress);
            byte[] byteIP   = iPAddress.GetAddressBytes();
            uint   ipInUint = (uint)byteIP[0];

            return(ipInUint);
        }
Пример #41
0
        public override void Serialize(ref SerializationWriter mySerializationWriter)
        {
            mySerializationWriter.CheckNull("mySerializationWriter");

            if (_IPAddress != null)
            {
                mySerializationWriter.WriteBytesDirect(_IPAddress.GetAddressBytes());
            }
        }
Пример #42
0
        /// <summary>
        /// Encodes the ip address.
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="ipAddress">The ip address.</param>
        /// <returns>offset as int</returns>
        private static int EncodeIPAddress(this byte[] bytes, int offset, System.Net.IPAddress ipAddress)
        {
            offset = bytes.EncodeClassConstructType(offset, Asn1Class.Application, ConstructType.Primitive, (byte)Asn1SnmpTag.IpAddress);
            offset = bytes.EncodeLength(offset, 4);

            byte[] bytesEncoded = ipAddress.GetAddressBytes();
            Array.Copy(bytesEncoded, 0, bytes, offset, bytesEncoded.Length);
            return(offset + 4);
        }
Пример #43
0
        private uint GetIP(string strIp)
        {
            System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(strIp);
            uint lIp = BitConverter.ToUInt32(ipaddress.GetAddressBytes(), 0);

            //調整IP地址的字節序
            lIp = ((lIp & 0xFF000000) >> 24) + ((lIp & 0x00FF0000) >> 8) + ((lIp & 0x0000FF00) << 8) + ((lIp & 0x000000FF) << 24);
            return(lIp);
        }
        public static IPAddressMessage Convert(this System.Net.IPAddress address)
        {
            switch (address.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                return(new IPAddressMessage {
                    IpV4 = address.GetAddressBytes().ToUInt32()
                });

            case AddressFamily.InterNetworkV6:
                return(new IPAddressMessage {
                    IpV6 = ByteString.CopyFrom(address.GetAddressBytes())
                });

            default:
                return(null);
            }
        }
Пример #45
0
        public static Network.IPAddress ToArke(System.Net.IPAddress ip)
        {
            if (ip == null)
            {
                throw new ArgumentNullException(nameof(ip));
            }

            return(new Network.IPAddress(ip.GetAddressBytes()));
        }
Пример #46
0
        public static System.Net.IPAddress Not(System.Net.IPAddress mask)
        {
            byte[] mm = mask.GetAddressBytes();

            for (int i = 0; i < mm.Length; i++)
            {
                mm[i] = (byte)(~mm[i]);
            }
            return(new System.Net.IPAddress(mm));
        }
Пример #47
0
        static public System.Net.IPAddress Minus(System.Net.IPAddress x, byte y)
        {
            byte[] New = Minus(x.GetAddressBytes(), y);
            string ni  = New.Length == 4 ? string.Format("{0}.{1}.{2}.{3}", New[0], New[1], New[2], New[3])
                                        : string.Format("{0:x2}{1:x2}:{2:x2}{3:x2}:{4:x2}{5:x2}:{6:x2}{7:x2}:{8:x2}{9:x2}:{10:x2}{11:x2}:{12:x2}{13:x2}:{14:x2}{15:x2}",
                                                        New[0], New[1], New[2], New[3], New[4], New[5], New[6], New[7],
                                                        New[8], New[9], New[10], New[11], New[12], New[13], New[14], New[15]);

            return(System.Net.IPAddress.Parse(ni));
        }
Пример #48
0
        private long IPAddressToLong(string IPAddr)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
            byte[] byteIP            = oIP.GetAddressBytes();
            long   ip = (long)byteIP[3] << 24;

            ip += (long)byteIP[2] << 16;
            ip += (long)byteIP[1] << 8;
            ip += (long)byteIP[0];
            return(ip);
        }
Пример #49
0
    public static long IPtoLong(System.Net.IPAddress theIP) // convert IP to number
    {
        byte[] IPb  = theIP.GetAddressBytes();              // get the octets
        long   addr = 0;                                    // accumulator for address

        for (int x = 0; x <= 3; x++)
        {
            addr |= (System.Convert.ToInt64(IPb[x]) << (3 - x) * 8);
        }
        return(addr);
    }
Пример #50
0
        static public int CompareFor(System.Net.IPAddress x, System.Net.IPAddress y)
        {
            if ((x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork &&
                 y.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ||
                (x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 &&
                 y.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6))
            {
                return(IPSeg.CompareFor(x.GetAddressBytes(), y.GetAddressBytes()));
            }

            throw new Exception("IP地址类型必须是IPv4或者IPv6才能进行比较");
        }
Пример #51
0
 public static int IpToInt(string address)
 {
     System.Net.IPAddress ip = null;
     if (System.Net.IPAddress.TryParse(address.Trim(), out ip))
     {
         return(BitConverter.ToInt32(ip.GetAddressBytes(), 0));
     }
     else
     {
         return(0);
     }
 }
Пример #52
0
        /// <summary>
        /// Converts IP address to number.
        /// </summary>
        /// <param name="IPAddr">IP address.</param>
        /// <returns>IP address in number format.</returns>
        private static uint IPAddressToLongBackwards(string IPAddr)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
            byte[] byteIP            = oIP.GetAddressBytes();

            uint ip = (uint)byteIP[0] << 24;

            ip += (uint)byteIP[1] << 16;
            ip += (uint)byteIP[2] << 8;
            ip += (uint)byteIP[3];

            return(ip);
        }
Пример #53
0
        /// <summary>
        /// Converts a string representation of an IP address to a uint. This
        /// encoding is proper and can be used with other networking functions such
        /// as the System.Net.IPAddress class.
        /// </summary>
        /// <param name="IPAddress">The Ip address to convert.</param>
        /// <returns>Returns a uint representation of the IP address.</returns>
        static public uint IPAddressToLong(string IPAddress)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddress);
            byte[] byteIP            = oIP.GetAddressBytes();


            uint ip = (uint)byteIP[3] << 24;

            ip += (uint)byteIP[2] << 16;
            ip += (uint)byteIP[1] << 8;
            ip += (uint)byteIP[0];

            return(ip);
        }
Пример #54
0
        public static bool InSubnet(System.Net.IPAddress IPAddr, string Subnet)
        {
            bool result = false;

            int  cidr = Int32.Parse(Subnet.Split('/')[1]);
            uint mask = cidr == 0 ? 0 : 0xffffffff << (32 - cidr);

            byte[] maskBytes = BitConverter.GetBytes(mask);
            Array.Reverse(maskBytes);

            byte[]    addressBytes = IPAddr.GetAddressBytes();
            IPAddress subnet       = IPAddress.Parse(Subnet.Split('/')[0]);

            byte[] maskedAddressBytes = new byte[addressBytes.Length];

            for (int i = 0; i < maskedAddressBytes.Length; i++)
            {
                maskedAddressBytes[i] = (byte)(IPAddr.GetAddressBytes()[i] & maskBytes[i]);
            }
            IPAddress maskedAddress = new IPAddress(maskedAddressBytes);

            result = (subnet.Equals(maskedAddress));
            return(result);
        }
Пример #55
0
        private int ProcessCHandshake(Protocol _p)
        {
            Handshake.CHandshake p = (Handshake.CHandshake)_p;
            int group = p.Argument.dh_group;

            if (false == Config.HandshakeOptions.DhGroups.Contains(group))
            {
                p.Sender.Close(new Exception("dhGroup Not Supported"));
                return(0);
            }
            Array.Reverse(p.Argument.dh_data);
            BigInteger data = new BigInteger(p.Argument.dh_data);
            BigInteger rand = Handshake.Helper.makeDHRandom();

            byte[] material = Handshake.Helper.computeDHKey(group, data, rand).ToByteArray();
            Array.Reverse(material);
            System.Net.IPAddress ipaddress =
                ((IPEndPoint)p.Sender.Socket.LocalEndPoint).Address;
            //logger.Debug(ipaddress);
            if (ipaddress.IsIPv4MappedToIPv6)
            {
                ipaddress = ipaddress.MapToIPv4();
            }
            byte[] key = Config.HandshakeOptions.SecureIp != null
                ? Config.HandshakeOptions.SecureIp
                : ipaddress.GetAddressBytes();
            logger.Debug("{0} localip={1}", p.Sender.SessionId, BitConverter.ToString(key));
            int half = material.Length / 2;

            byte[] hmacMd5 = Digest.HmacMd5(key, material, 0, half);
            p.Sender.SetInputSecurityCodec(hmacMd5, Config.HandshakeOptions.C2sNeedCompress);
            byte[] response = Handshake.Helper.generateDHResponse(group, rand).ToByteArray();
            Array.Reverse(response);
            new Handshake.SHandshake(response,
                                     Config.HandshakeOptions.S2cNeedCompress,
                                     Config.HandshakeOptions.C2sNeedCompress)
            .Send(p.Sender);
            hmacMd5 = Digest.HmacMd5(key, material, half, material.Length - half);
            p.Sender.SetOutputSecurityCodec(hmacMd5, Config.HandshakeOptions.S2cNeedCompress);

            // 为了防止服务器在Handshake以后马上发送数据,
            // 导致未加密数据和加密数据一起到达Client,这种情况很难处理。
            // 这个本质上是协议相关的问题:就是前面一个协议的处理结果影响后面数据处理。
            // 所以增加CHandshakeDone协议,在Client进入加密以后发送给Server。
            // OnHandshakeDone(p.Sender);

            return(0);
        }
Пример #56
0
        private static System.Net.IPAddress BitOperate(System.Net.IPAddress x, System.Net.IPAddress mask, Operate op)
        {
            byte[] xx = x.GetAddressBytes();
            byte[] mm = mask.GetAddressBytes();
            if (xx.Length != mm.Length)
            {
                throw new ApplicationException("IP地址版本不一致,不能执行“或”操作");
            }
            int i = 0;

            for (i = 0; i < xx.Length; i++)
            {
                xx[i] = op(xx[i], mm[i]);
            }
            return(new System.Net.IPAddress(xx));
        }
Пример #57
0
        /// <summary>
        /// Returns true if the IPAddress supplied is on the same subnet as this host
        /// </summary>
        public static bool IsLocal(NetAddress remote)
        {
            var local = GetMyAddress(out var mask);

            if (mask == null)
            {
                return(false);
            }

            uint maskBits   = BitConverter.ToUInt32(mask.GetAddressBytes(), 0);
            uint remoteBits = BitConverter.ToUInt32(remote.GetAddressBytes(), 0);
            uint localBits  = BitConverter.ToUInt32(local.GetAddressBytes(), 0);

            // compare network portions
            return((remoteBits & maskBits) == (localBits & maskBits));
        }
        public static System.Net.IPAddress GetNetworkAddress(System.Net.IPAddress address, System.Net.IPAddress subnetMask)
        {
            byte[] ipAdressBytes   = address.GetAddressBytes();
            byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

            if (ipAdressBytes.Length != subnetMaskBytes.Length)
            {
                throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
            }

            byte[] broadcastAddress = new byte[ipAdressBytes.Length];
            for (int i = 0; i < broadcastAddress.Length; i++)
            {
                broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
            }
            return(new System.Net.IPAddress(broadcastAddress));
        }
    //Возвращает число единичных бит в маске
    private int mask_to_short_form(System.Net.IPAddress mask)
    {
        byte[] bytes          = mask.GetAddressBytes();
        int    number_of_bits = 0;

        foreach (var _octet in bytes)
        {
            byte octet = _octet;

            while (octet != 0)
            {
                number_of_bits += octet & 1;
                octet         >>= 1;
            }
        }

        return(number_of_bits);
    }
Пример #60
0
        private static string GetMacString(System.Net.IPAddress ip)
        {
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                byte[] mac    = new byte[6];
                int    macLen = mac.Length;

                int dest = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
                int res  = NativeMethods.SendARP(dest, 0, mac, ref macLen);

                if ((res == 0) && ((mac[0] != 0) || (mac[1] != 0) || (mac[2] != 0) || (mac[3] != 0) || (mac[4] != 0) || (mac[5] != 0)))
                {
                    return((mac[0].ToString("x2") + ":" + mac[1].ToString("x2") + ":" + mac[2].ToString("x2") + ":" + mac[3].ToString("x2") + ":" + mac[4].ToString("x2") + ":" + mac[5].ToString("x2")).ToUpper());
                }
            }

            return(null);
        }