標籤:c# 擷取本機 內網 外網 ip
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"; }
C#擷取本機內網外網IP