3

I want to get the IP of my PC (the local IP taken from the router).

I could get the IP but with other IPs on the network. Is there a method to extract only the needed IP without getting all the IPs in an array and then choosing from them the needed one?

Code tried:

string strHostName = string.Empty;
strHostName = Dns.GetHostName();
IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);
IPAddress[] address = ipHostEntry.AddressList;

foreach (var item in address)
{
    Console.WriteLine(item.ToString());
}

The result of this code is a bunch of IPs found on the network including my IP (broadcast domain, IPv6 and similar stuff but not other devices' IPs). I want to get only my actual IP without getting all as the code will be published on a machine which I cannot monitor the IP all the time.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
TheCondorIV
  • 574
  • 2
  • 14
  • 34
  • 2
    *The* ip does not exist, it depends on the number of interfaces on your system. You should take care of all of them or specifically look for one interface. – Rob Jul 29 '19 at 07:13
  • 1
    And if you want to know the IP Address of the interface that you connect to the internet with, [this](https://stackoverflow.com/a/27376368/9363973) SO answer has a solution to it – MindSwipe Jul 29 '19 at 07:14

1 Answers1

6

You are missing to filter the IP by type (v4). Anyway you can have multiple IP v4 addresses on your PC (for example you can have 2 interfaces, LAN and Wi-Fi).

The following code gets the list of available IP v4.

List<string> ips = new List<string>();

System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

foreach (System.Net.IPAddress ip in entry.AddressList)
    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
        ips.Add(ip.ToString());