C# 获取本地计算机IP地址


1
/// <summary> 2 /// 获取ip地址 3 /// </summary> 4 /// <returns></returns> 5 public string GetLocalIP() 6 { 7 try 8 { 9 string HostName = Dns.GetHostName(); //得到主机名 10 IPHostEntry IpEntry = Dns.GetHostEntry(HostName); 11 for (int i = 0; i < IpEntry.AddressList.Length; i++) 12 { 13 //从IP地址列表中筛选出IPv4类型的IP地址 14 //AddressFamily.InterNetwork表示此IP为IPv4, 15 //AddressFamily.InterNetworkV6表示此地址为IPv6类型 16 if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) 17 { 18 return IpEntry.AddressList[i].ToString(); 19 } 20 } 21 return ""; 22 } 23 catch (Exception ex) 24 { 25 MessageBox.Show("获取本机IP出错:" + ex.Message); 26 return ""; 27 } 28 }

 

对于web访问后台接口时的IP地址防区方法:

///获取本地的IP地址
            string AddressIP = System.Web.HttpContext.Current.Request.UserHostAddress;

 

posted @ 2020-06-15 12:03  幸运(● ̄(エ) ̄●)  阅读(597)  评论(0编辑  收藏  举报
Document