2019-9-2-win10-uwp-判断本地ip

title author date CreateTime categories
win10 uwp 判断本地ip
lindexi
2019-09-02 12:57:38 +0800
2018-2-13 17:23:3 +0800
Win10 UWP

本文主要:如何判断一个IP是本地IP

对于本地 127.0.0.1 就是一个内部IP,之外,还有10.0.0.0/24172.16.0.0/16192.168.0.0/16169.254.0.0/16

判断是不是本地,首先判断是不是127.0.0.1

        private bool IsPrivateIP(IPAddress myIPAddress)
        {
            if (IPAddress.IsLoopback(myIPAddress))
            {
                return true;
            }
        }

判断是不是10.0.0.0/24

            byte[] ipBytes = myIPAddress.GetAddressBytes();
            // 10.0.0.0/24 
            if (ipBytes[0] == 10)
            {
                return true;
            }

判断172.16.0.0/16

                if (ipBytes[0] == 172 && ipBytes[1] == 16)
                {
                    return true;
                }

判断192.168.0.0/16

                if (ipBytes[0] == 192 && ipBytes[1] == 168)
                {
                    return true;
                }

判断169.254.0.0/16

                if (ipBytes[0] == 169 && ipBytes[1] == 254)
                {
                    return true;
                }

源代码:

        /// <summary>
        /// 判断私有ip
        /// </summary>
        /// <param name="myIPAddress"></param>
        /// <returns></returns>
        private bool IsPrivateIP(IPAddress myIPAddress)
        {
            if (IPAddress.IsLoopback(myIPAddress))
            {
                return true;
            }
            if (myIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                byte[] ipBytes = myIPAddress.GetAddressBytes();
                // 10.0.0.0/24 
                if (ipBytes[0] == 10)
                {
                    return true;
                }
                // 172.16.0.0/16
                else if (ipBytes[0] == 172 && ipBytes[1] == 16)
                {
                    return true;
                }
                // 192.168.0.0/16
                else if (ipBytes[0] == 192 && ipBytes[1] == 168)
                {
                    return true;
                }
                // 169.254.0.0/16
                else if (ipBytes[0] == 169 && ipBytes[1] == 254)
                {
                    return true;
                }
            }
            return false;
        }
原文地址:https://www.cnblogs.com/lindexi/p/12085479.html