C#如何获取本机的外网ip地址?
源码如下:
public static string GetextenalIP() { //获取外部IP String url = "http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp"; string IP = "未获取到外网ip"; try { //从网址中获取本机ip数据 System.Net.WebClient client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.Default; string str = client.DownloadString(url); client.Dispose(); if (!str.Equals("")) IP = str; else IP = GetExtenalIpAddress_0(); } catch (Exception) { } return IP; } public static string GetExtenalIpAddress_0() { string IP = "未获取到外网ip"; try { //从网址中获取本机ip数据 System.Net.WebClient client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.Default; string str = client.DownloadString("http://1111.ip138.com/ic.asp"); client.Dispose(); //提取外网ip数据 [218.104.71.178] int i1 = str.IndexOf("["), i2 = str.IndexOf("]"); IP = str.Substring(i1 + 1, i2 - 1 - i1); } catch (Exception) { } return IP; }
如何调用获取ip地址?
可以将ip地址写入label标签中
label.text= GetextenalIP();