【转载】c# 获取本地主机的ip地址四种方法

时间:2024-02-22 13:51:55

1. 获取本机IP地址四种方法

第一种  取本机IP地址:

 public string GetLocalIp()
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        } 

第二种  取本机IP地址:

         /// <summary>
        /// 取本机主机ip
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            try
            {
                
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        string ip = "";
                        ip = IpEntry.AddressList[i].ToString();
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

第三种 取本机IP地址:

public static string GetIp { get; } = Dns.GetHostEntry(Dns.GetHostName()).
            AddressList.FirstOrDefault(p => p.AddressFamily.ToString() == "InterNetwork")?.ToString();

第四种 通过访问的网址来取IP:

 public static string GetIP()
        {
            using (var webClient = new WebClient())
            {
                try
                {
                    var temp = webClient.DownloadString("http://localhost:1234/WeatherWebForm.aspx");//一般指定网址
                    var ip = Regex.Match(temp, @"\[(?<ip>\d+\.\d+\.\d+\.\d+)]").Groups["ip"].Value;
                    return !string.IsNullOrEmpty(ip) ? ip : null;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
        }

2. 使用实例

第一种方式和三种方式的使用实例,,如图所示:

 3. 参考资料

https://blog.csdn.net/technologyleader/article/details/83067998