C#如何获取本机的外网ip地址?

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();

 

原文地址:http://www.zhating.cn/index.php/post/89.html

更多C#文章请点击:http://www.zhating.cn/index.php/category-4_2.html

你可能感兴趣的:(C#编程常见问题集锦,C#编程分享)