How to get *internet* IP?

后端 未结 15 2120
刺人心
刺人心 2020-11-29 02:57

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 wi

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 03:52

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

    Edit History:

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

提交回复
热议问题