2个不同的IP地址
2 Different IP Address
我的程序中有 2 种方法来检索计算机的 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;
}
第一个代码returns一个看起来像10.xx.xx.x的IP,第二个代码returns IP 地址如121.xx.xx.xx
为什么这两种方法的输出不同?
在第一种方法中,您获取的是内部网络的 IP 地址,因此如果您在路由器后面,您将获得一个内部 IP 地址。这是您在命令提示符下 运行 ipconfig /all
时会看到的地址。
在第二种方法中,您将获取互联网(外部)IP 地址。
显然,您落后于某些 NAT。
因此,通过 运行 第一个代码,您将收到您的内部网络地址,第二个代码为您提供真实的(外部)IP 地址,您的网络可以从该地址访问 Internet。
因为第二种方法只是调用外部网站确定您的IP,而该网站只能确定真实IP地址,不能确定内部IP。
我的程序中有 2 种方法来检索计算机的 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;
}
第一个代码returns一个看起来像10.xx.xx.x的IP,第二个代码returns IP 地址如121.xx.xx.xx
为什么这两种方法的输出不同?
在第一种方法中,您获取的是内部网络的 IP 地址,因此如果您在路由器后面,您将获得一个内部 IP 地址。这是您在命令提示符下 运行 ipconfig /all
时会看到的地址。
在第二种方法中,您将获取互联网(外部)IP 地址。
显然,您落后于某些 NAT。
因此,通过 运行 第一个代码,您将收到您的内部网络地址,第二个代码为您提供真实的(外部)IP 地址,您的网络可以从该地址访问 Internet。
因为第二种方法只是调用外部网站确定您的IP,而该网站只能确定真实IP地址,不能确定内部IP。