I need to find out the local Ip address, for that reason I was using the following code:
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
return localIP;
I find out that when a PC has more than one IP with AddressFamily.InterNetwork
I get always the first one. However I can't find any property to find out the active IP.
How can I get the correct IP?
Thanks for any tip!
Bwall has a fitting solution posted in this thread.
The important thing in this piece of code is, that it only lists IP addresses of ethernet and wireless interfaces. I doubt you'll have a serial connection active, so this won't matter most likely. Alternativly you can always edit the if statement.
//EDIT If you only want to IP address which actually connects to the internet use Hosam Aly's solution
This is his code:
What it basically does, is trace the route to www.example.com and processes the right IP from there. I tested the code on my machine and needed to change the iterations from 9 to 5 to get the right line from stream. You better recheck it or you might into a NullReferenceException because
line
will benull
.I have picked this up from internet a while ago.
This should give you an array of all the ip addresses of your pc.