MapToIPv4() public method

public MapToIPv4 ( ) : IPAddress
return IPAddress
        public void Connect(int aPort, IPAddress Ip, string userName, string password, string nick)
        {
            int attempts = 5;
            _nick = nick;

            // TODO: validar esse objeto, pois após a desconexão ocorre o dispose() dele
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            while (!_clientSocket.Connected && attempts > 0)
            {
                try
                {
                    OnRaiseMessage(new MessageEventArgs(String.Format("Attempt {0} to connect at server {1}:{2}", attempts, Ip.MapToIPv4().Address, aPort)));
                    _clientSocket.Connect(Ip ,aPort);
                    OnRaiseMessage(new MessageEventArgs("Connected!"));

                    //solicita autenticação
                    Authenticate(userName, password);

                    //inicia recebimento assíncrono de mensagens
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket);

                }
                catch (Exception ex)
                {
                    OnRaiseMessage(new MessageEventArgs("Connection failed."));
                    Thread.Sleep(1000);
                    attempts--;
                }
            }
        }
Beispiel #2
0
 private static string _ExtractNetworkId(IPAddress ipaddress)
 {
     var fam = ipaddress.AddressFamily == AddressFamily.InterNetwork;
     var parts = ipaddress.MapToIPv4().ToString().Split(new[] {'.'}).Take(3);
     var networkId = string.Join(".", parts);
     return networkId;
 }
Beispiel #3
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.");
        }
Beispiel #4
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);
        }
Beispiel #5
0
        public bool IsLocal(IPAddress address)
        {
            if (_dict.ContainsKey(address))
                return true;

            if (IPAddress.IsLoopback(address))
                return true;

            if (address.IsIPv4MappedToIPv6)
            {
                var ip4 = address.MapToIPv4();
                if (_dict.ContainsKey(ip4))
                    return true;
            }

            return false;
        }
Beispiel #6
0
        /// <summary>
        /// An extension method to determine if an IP address is internal, as specified in RFC1918
        /// </summary>
        /// <param name="ip">The IP address that will be tested</param>
        /// <returns>Returns true if the IP is internal, false if it is external</returns>
        public static bool IsInternal(this System.Net.IPAddress ip)
        {
            if (ip.IsIPv4MappedToIPv6)
            {
                ip = ip.MapToIPv4();
            }
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                byte[] bytes = ip.GetAddressBytes();
                switch (bytes[0])
                {
                case 10:
                case 127:
                    return(true);

                case 172:
                    return(bytes[1] >= 16 && bytes[1] < 32);

                case 192:
                    return(bytes[1] == 168);

                default:
                    return(bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0 && bytes[3] == 0);
                }
            }

            string addressAsString = ip.ToString();
            string firstWord       = addressAsString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0];

            // equivalent of 127.0.0.1 in IPv6
            if (addressAsString == "::1")
            {
                return(true);
            }

            // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
            else if (ip.IsIPv6SiteLocal)
            {
                return(true);
            }

            // These days Unique Local Addresses (ULA) are used in place of Site Local.
            // ULA has two variants:
            //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central).
            //      fd00::/8 is in use and does not have to registered anywhere.
            else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fc")
            {
                return(true);
            }
            else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fd")
            {
                return(true);
            }
            // Link local addresses (prefixed with fe80) are not routable
            else if (firstWord == "fe80")
            {
                return(true);
            }
            // Discard Prefix
            else if (firstWord == "100")
            {
                return(true);
            }

            // Any other IP address is not Unique Local Address (ULA)
            return(false);
        }
Beispiel #7
0
        public static bool IsAddressPrivate(NetAddress address)
        {
            if (address.AddressFamily == AddressFamily.InterNetworkV6 && address.IsIPv4MappedToIPv6)
            {
                address = address.MapToIPv4();
            }

            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                byte[] bytes = address.GetAddressBytes();
                return(bytes[0] == 10 ||
                       bytes[0] == 127 ||
                       (bytes[0] == 192 && bytes[1] == 168) ||
                       (bytes[0] == 172 && (bytes[1] >= 16 && bytes[1] <= 31)));
            }
            else if (address.AddressFamily == AddressFamily.InterNetworkV6)
            {
                string addressAsString = address.ToString();

                // equivalent of 127.0.0.1 in IPv6
                if (addressAsString == "::1")
                {
                    return(true);
                }

                // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
                if (address.IsIPv6SiteLocal)
                {
                    return(true);
                }

                int idx = addressAsString.IndexOf(':');
                if (idx == -1)
                {
                    return(false);
                }

                string firstWord = addressAsString.Substring(0, idx);

                // These days Unique Local Addresses (ULA) are used in place of Site Local.
                // ULA has two variants:
                //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central).
                //      fd00::/8 is in use and does not have to registered anywhere.
                if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fc")
                {
                    return(true);
                }
                if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fd")
                {
                    return(true);
                }

                // Link local addresses (prefixed with fe80) are not routable
                if (firstWord == "fe80")
                {
                    return(true);
                }

                // Discard Prefix
                if (firstWord == "100")
                {
                    return(true);
                }

                // Any other IP address is not Unique Local Address (ULA)
                return(false);
            }

            return(false);
        }