How to get *internet* IP?

后端 未结 15 2089
刺人心
刺人心 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:38

    You could simply read http://myip.dnsomatic.com/

    It's a reliable service by OpenDNS, and I use it to get the external IP all the time.

    0 讨论(0)
  • 2020-11-29 03:40

    I suggest this simple code since tracert is not always effective and whatsmyip.com is not specially designed for that purpose :

    private void GetIP()
    {
        WebClient wc = new WebClient();
        string strIP = wc.DownloadString("http://checkip.dyndns.org");
        strIP = (new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")).Match(strIP).Value;
        wc.Dispose();
        return strIP;
    }
    
    0 讨论(0)
  • 2020-11-29 03:42

    This is my attempt to get the default IPv4 address without having to resort to DNS or external process calls to commands like ipconfig and route. Hopefully the next version of .Net will provide access to the Windows routing table.

    public static IPAddress GetDefaultIPv4Address()
    {
        var adapters = from adapter in NetworkInterface.GetAllNetworkInterfaces()
                       where adapter.OperationalStatus == OperationalStatus.Up &&
                        adapter.Supports(NetworkInterfaceComponent.IPv4)
                        && adapter.GetIPProperties().GatewayAddresses.Count > 0 &&
                        adapter.GetIPProperties().GatewayAddresses[0].Address.ToString() != "0.0.0.0"
                       select adapter;
    
         if (adapters.Count() > 1)
         {
              throw new ApplicationException("The default IPv4 address could not be determined as there are two interfaces with gateways.");
         }
         else
         {
             UnicastIPAddressInformationCollection localIPs = adapters.First().GetIPProperties().UnicastAddresses;
             foreach (UnicastIPAddressInformation localIP in localIPs)
             {
                if (localIP.Address.AddressFamily == AddressFamily.InterNetwork &&
                    !localIP.Address.ToString().StartsWith(LINK_LOCAL_BLOCK_PREFIX) &&
                    !IPAddress.IsLoopback(localIP.Address))
                {
                    return localIP.Address;
                }
            }
        }
    
        return null;
    }
    
    0 讨论(0)
  • 2020-11-29 03:44

    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

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-11-29 03:52

    in the same direction as Lukas Šalkauskas, a friend of mine and I wrote this code:

       /* digged, built and (here and there) copied "as is" from web, without paying attention to style.
        Please, do not shot us for this. 
       */
    public static void DisplayIPAddresses() 
        { 
    
            Console.WriteLine("\r\n****************************"); 
            Console.WriteLine("     IPAddresses"); 
            Console.WriteLine("****************************"); 
    
    
            StringBuilder sb = new StringBuilder(); 
            // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)      
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); 
    
            foreach (NetworkInterface network in networkInterfaces) 
            { 
    
                if (network.OperationalStatus == OperationalStatus.Up ) 
                { 
                    if (network.NetworkInterfaceType == NetworkInterfaceType.Tunnel) continue; 
                    if (network.NetworkInterfaceType == NetworkInterfaceType.Tunnel) continue; 
                    //GatewayIPAddressInformationCollection GATE = network.GetIPProperties().GatewayAddresses; 
                    // Read the IP configuration for each network    
    
                    IPInterfaceProperties properties = network.GetIPProperties(); 
                    //discard those who do not have a real gateaway  
                    if (properties.GatewayAddresses.Count > 0) 
                    { 
                        bool good = false; 
                        foreach  (GatewayIPAddressInformation gInfo in properties.GatewayAddresses) 
                        { 
                            //not a true gateaway (VmWare Lan) 
                            if (!gInfo.Address.ToString().Equals("0.0.0.0")) 
                            { 
                                sb.AppendLine(" GATEAWAY "+ gInfo.Address.ToString()); 
                                good = true; 
                                break; 
                            } 
                        } 
                        if (!good) 
                        { 
                            continue; 
                        } 
                    } 
                    else { 
                        continue; 
                    } 
                    // Each network interface may have multiple IP addresses        
                    foreach (IPAddressInformation address in properties.UnicastAddresses) 
                    { 
                        // We're only interested in IPv4 addresses for now        
                        if (address.Address.AddressFamily != AddressFamily.InterNetwork) continue; 
    
                        // Ignore loopback addresses (e.g., 127.0.0.1)     
                        if (IPAddress.IsLoopback(address.Address)) continue; 
    
                        if (!address.IsDnsEligible) continue; 
                        if (address.IsTransient) continue;  
    
                        sb.AppendLine(address.Address.ToString() + " (" + network.Name + ") nType:" + network.NetworkInterfaceType.ToString()     ); 
                    } 
                } 
            } 
            Console.WriteLine(sb.ToString()); 
        }
    
    0 讨论(0)
提交回复
热议问题