c# 获取本地主机的ip地址三种方法

时间:2025-01-27 15:02:39

第一种     取本主机ip地址

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

第二种     

        /// <summary>
        /// 取本机主机ip
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            try
            {
                
                string HostName = (); //得到主机名
                IPHostEntry IpEntry = (HostName);
                for (int i = 0; i < ; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if ([i].AddressFamily == )
                    {
                        string ip = "";
                        ip = [i].ToString();
                        return [i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return ;
            }
        }
第三种 通过访问的网址来取IP

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