using System.Net; //获取本地ip地址 public String GetLocalIpAddress() { IPAddress[] names = Dns.GetHostAddresses(Dns.GetHostName()); if (Dns.GetHostAddresses(Dns.GetHostName()).Length > 1) return Dns.GetHostAddresses(Dns.GetHostName())[1].ToString(); else return Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(); }
<span style="white-space:pre"> </span>//获取外网ip地址 public string GetExtenalIpAddress() { try { //从网址中获取本机ip数据 System.Net.WebClient client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.Default; string reply = client.DownloadString("http://1111.ip138.com/ic.asp"); //"http://www.ip138.com" //提取外网ip数据 [218.104.71.178] int i1 = reply.IndexOf("["), i2 = reply.IndexOf("]"); string IP = reply.Substring(i1 + 1, i2 - 1 - i1); if (!IP.Equals("")) return IP; } catch (Exception) { } return "未获取到外网ip"; }
原文地址:http://blog.csdn.net/scimence/article/details/44408783