Get All IP Addresses on Machine

前端 未结 6 622
北恋
北恋 2020-12-01 17:55

How can I get all of the IP addresses attached to the machine that my application (C# NET Console app) is running on? I need to bind a WCF service to the primary IP address,

相关标签:
6条回答
  • 2020-12-01 18:32

    You should probably bind to 0.0.0.0:8000, that will expose it on all available IP addresses and only bind to a particular IP address if the user/administrator demands so.

    0 讨论(0)
  • 2020-12-01 18:34

    Why not just bind to 0.0.0.0 ?
    That way you listen on all ips

    0 讨论(0)
  • 2020-12-01 18:37

    The DNS variants work across the network, but one DNS entry can have many IP addresses and one IP address can have many DNS entries. More importantly, an address needn't be bound to a DNS entry at all.

    For the local machine try this:-

      foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
      {
        Console.WriteLine("Name: " + netInterface.Name);
        Console.WriteLine("Description: " + netInterface.Description);
        Console.WriteLine("Addresses: ");
        IPInterfaceProperties ipProps = netInterface.GetIPProperties();
        foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
        {
          Console.WriteLine(" " + addr.Address.ToString());
        }
        Console.WriteLine("");
      }
    
    0 讨论(0)
  • 2020-12-01 18:38
    IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
    
    0 讨论(0)
  • 2020-12-01 18:39

    I think this example should help you.

    // Get host name
    String strHostName = Dns.GetHostName();
    
    // Find host by name
    IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
    
    // Enumerate IP addresses
    foreach(IPAddress ipaddress in iphostentry.AddressList)
    {
        ....
    }
    

    Edit:

    "There's no such thing as a "primary" IP address.

    The routing table determines which outward-facing IP address is used depending on the destination IP address (and by extension, the network interface, which itself can be virtual or physical)."

    0 讨论(0)
  • 2020-12-01 18:47

    I think the OP is asking about how to get all addresses on a local NIC, not just those addresses known to DNS. By primary he probably means the main address under "use the following IP address" in the adapter properties, and by "the rest" he probably means those listed in Advanced > (Additional) IP Addesses.

    DNS will not necessarily know those.

    0 讨论(0)
提交回复
热议问题