【轉載】c# 獲取本地主機的ip地址四種方法

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章