【发布时间】:2015-02-20 14:39:56
【问题描述】:
我的程序中有两种方法可以检索计算机的 IP 地址。
第一
public string GetIP1()
{
//using System.Net.Sockets;
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
}
第二次
public string GetIP2()
{
//using System.IO;
String direction = "";
try
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
}
catch(Exception){ }
return direction;
}
第一个代码返回一个类似于 10.xx.xx.x 的 IP,第二个代码返回一个 IP 地址,例如 121.xx.xx.xx
为什么这两种方法的输出不同?
【问题讨论】:
-
你有两个不同的网络适配器吗?
-
那么没有 WiFi 适配器。我想你不是在笔记本上开发。
-
请从第一个代码中删除
FirstOrDefault,看看第二个IP是否也来自第一个代码的集合。 -
是的,我没有 wifi 适配器...而且我正在使用台式机
标签: c# ip-address