How to get *internet* IP?

后端 未结 15 2124
刺人心
刺人心 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: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;
    }
    

提交回复
热议问题