C# 如何获得*互联网* IP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/515436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get *internet* IP?
提问by Lukas ?alkauskas
Imagine a situation, I have PC with two lan cards, one is connected to internet another is connected to local network, how can I detect IP which is connected to internet with C# ?
想象一种情况,我有两个网卡,一个连接到互联网,另一个连接到本地网络,我如何使用 C# 检测连接到互联网的 IP?
采纳答案by Hosam Aly
Try this:
尝试这个:
static IPAddress getInternetIPAddress()
{
try
{
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress gateway = IPAddress.Parse(getInternetGateway());
return findMatch(addresses, gateway);
}
catch (FormatException e) { return null; }
}
static string getInternetGateway()
{
using (Process tracert = new Process())
{
ProcessStartInfo startInfo = tracert.StartInfo;
startInfo.FileName = "tracert.exe";
startInfo.Arguments = "-h 1 208.77.188.166"; // www.example.com
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
tracert.Start();
using (StreamReader reader = tracert.StandardOutput)
{
string line = "";
for (int i = 0; i < 9; ++i)
line = reader.ReadLine();
line = line.Trim();
return line.Substring(line.LastIndexOf(' ') + 1);
}
}
}
static IPAddress findMatch(IPAddress[] addresses, IPAddress gateway)
{
byte[] gatewayBytes = gateway.GetAddressBytes();
foreach (IPAddress ip in addresses)
{
byte[] ipBytes = ip.GetAddressBytes();
if (ipBytes[0] == gatewayBytes[0]
&& ipBytes[1] == gatewayBytes[1]
&& ipBytes[2] == gatewayBytes[2])
{
return ip;
}
}
return null;
}
Note that this implementation of findMatch()
relies on class C matching. If you want to support class B matching, just omit the check for ipBytes[2] == gatewayBytes[2]
.
请注意,此实现findMatch()
依赖于 C 类匹配。如果您想支持 B 类匹配,只需省略对ipBytes[2] == gatewayBytes[2]
.
Edit History:
编辑历史:
- Updated to use
www.example.com
. - Updated to include
getInternetIPAddress()
, to show how to use the other methods. - Updated to catch
FormatException
ifgetInternetGateway()
failed to parse the gateway IP. (This can happen if the gateway router is configured such that it doesn't respond to tracerouterequests.) - Cited Brian Rasmussen's comment.
- Updated to use the IP for www.example.com, so that it works even when the DNS server is down.
- 更新为使用
www.example.com
. - 更新为 include
getInternetIPAddress()
,以展示如何使用其他方法。 FormatException
如果getInternetGateway()
无法解析网关 IP,则更新为捕获。(如果网关路由器配置为不响应traceroute请求,就会发生这种情况。)- 引用了 Brian Rasmussen 的评论。
- 更新为使用 www.example.com 的 IP,以便即使在 DNS 服务器关闭时它也能工作。
回答by xyz
A hacky way is to fetch and scrape one of the many 'What Is My IP' type websites.
一种黑客方法是获取和抓取众多“我的 IP 是什么”类型的网站之一。
回答by Polo
I already search that, i found it in this codeplex project http://www.codeplex.com/xedus. It a none working P2P freeware but there is a class that use the right API to get the lan card witch has the internet ip
我已经搜索过了,我在这个 codeplex 项目http://www.codeplex.com/xedus 中找到了它。它是一个无效的 P2P 免费软件,但有一个类使用正确的 API 来获取具有互联网 IP 的局域网卡
回答by Brian Rasmussen
The internet connection must be on the same IP network as the default gateway.
Internet 连接必须与默认网关位于同一 IP 网络上。
There's really foolproof no way to tell from the IP address if you can reach the "internet" or not. Basically you can communicate with your own IP network. Everything else has to go through a gateway. So if you can't see the gateway, you're confined to the local IP network.
从 IP 地址判断您是否可以访问“互联网”真的是万无一失的。基本上您可以与您自己的 IP 网络进行通信。其他一切都必须通过网关。因此,如果您看不到网关,则您将被限制在本地 IP 网络中。
The gateway, however, depends on other gateways, so even if you can access the gateway, you may not be able to reach some other network. This can be due to e.g. filtering or lack of routes to the desired networks.
但是,网关依赖于其他网关,因此即使您可以访问网关,也可能无法访问其他网络。这可能是由于例如过滤或缺少到所需网络的路由。
Actually, it makes little sense to talk about the internet in this sense, as you will probably never be able to reach the entire internet at any given moment. Therefore, find out what you need to be able to reach and verify connectivity for that network.
实际上,在这个意义上谈论互联网毫无意义,因为您可能永远无法在任何特定时刻访问整个互联网。因此,找出您需要什么才能访问并验证该网络的连接性。
回答by Artelius
Not 100% accurate (some ISPs don't give you public IP addresses), but you can check if the IP address is on one of the ranges reserved for private addresses. See http://en.wikipedia.org/wiki/Classful_network
不是 100% 准确(一些 ISP 不给你公共 IP 地址),但你可以检查 IP 地址是否在为私有地址保留的范围之一内。见http://en.wikipedia.org/wiki/Classful_network
回答by Henrik Paul
For a quick hack (that will certainly become broken with elaborate LAN configurations or IPv6), get a list of all IPs the current machine has, and strip out all IP:s that match any of the following:
为了快速破解(这肯定会被精心设计的 LAN 配置或 IPv6 破坏),获取当前机器拥有的所有 IP 的列表,并去除与以下任何一项匹配的所有 IP:s:
10.* 127.* // <- Kudos to Brian for spotting the mistake 172.[16-31].* 192.168.*
回答by mouviciel
Try to ping www.google.com on both interfaces.
尝试在两个界面上 ping www.google.com。
回答by splattne
Here is an article which could be helpful:
这是一篇可能有用的文章:
How to Retrieve "Network Interfaces" in C#
The following code is used to retrieve the "network interfaces" in C#. You may recognize the "network interfaces" as "Network and Dial-up Connections": You can access them by using "Start > Setting > Network and Dial-up Connections". C# does not provide a simple way of retrieving this list.
以下代码用于检索 C# 中的“网络接口”。您可以将“网络接口”识别为“网络和拨号连接”:您可以通过使用“开始 > 设置 > 网络和拨号连接”来访问它们。C# 不提供检索此列表的简单方法。
回答by Lukas ?alkauskas
I found a solution:
我找到了一个解决方案:
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
Console.WriteLine(ipProperties.HostName);
foreach (NetworkInterface networkCard in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (GatewayIPAddressInformation gatewayAddr in networkCard.GetIPProperties().GatewayAddresses)
{
Console.WriteLine("Information: ");
Console.WriteLine("Interface type: {0}", networkCard.NetworkInterfaceType.ToString());
Console.WriteLine("Name: {0}", networkCard.Name);
Console.WriteLine("Id: {0}", networkCard.Id);
Console.WriteLine("Description: {0}", networkCard.Description);
Console.WriteLine("Gateway address: {0}", gatewayAddr.Address.ToString());
Console.WriteLine("IP: {0}", System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].ToString());
Console.WriteLine("Speed: {0}", networkCard.Speed);
Console.WriteLine("MAC: {0}", networkCard.GetPhysicalAddress().ToString());
}
}
回答by Can Berk Güder
You could simply read http://myip.dnsomatic.com/
你可以简单地阅读http://myip.dnsomatic.com/
It's a reliable service by OpenDNS, and I use it to get the external IP all the time.
这是 OpenDNS 提供的可靠服务,我一直使用它来获取外部 IP。