How to get the IP address of the server on which my C# application is running on?

Nefzen picture Nefzen · Jul 1, 2009 · Viewed 367.5k times · Source

I am running a server, and I want to display my own IP address.

What is the syntax for getting the computer's own (if possible, external) IP address?

Someone wrote the following code.

IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

However, I generally distrust the author, and I don't understand this code. Is there a better way to do so?

Answer

Andrew Hare picture Andrew Hare · Jul 1, 2009

Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.

Edit: The only thing I would change would be to change this:

if (ip.AddressFamily.ToString() == "InterNetwork")

to this:

if (ip.AddressFamily == AddressFamily.InterNetwork)

There is no need to ToString an enumeration for comparison.