如何获得*互联网* IP? [英] How to get *internet* IP?

查看:91
本文介绍了如何获得*互联网* IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试想一个情况,我有电脑有两个网卡,一个是连接到互联网的另一个连接到本地网络,如何检测IP连接到互联网的C#?

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# ?

推荐答案

试试这个:

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;
}

请注意,这个实施的findMatch()依赖于C类匹配。如果你想支持B类匹配,只是省略了检查 ipBytes [2] == gatewayBytes [2]

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].

修改历史:


  • 更新使用 www.example.com

  • 更新以包括 getInternetIPAddress(),来说明如何使用其他方法。

  • 更新搭上 FormatException 如果 getInternetGateway()无法解析网关的IP。 (如果网关路由器被配置为使得它不响应跟踪路由的请求可能发生这种情况。)

  • 引用布赖恩·拉斯穆森的评论。

  • 更新后可使用IP www.example.com的,所以它的作品甚至当DNS服务器已关闭。

  • Updated to use www.example.com.
  • Updated to include getInternetIPAddress(), to show how to use the other methods.
  • Updated to catch FormatException if getInternetGateway() failed to parse the gateway IP. (This can happen if the gateway router is configured such that it doesn't respond to traceroute requests.)
  • 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.

这篇关于如何获得*互联网* IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆