tags:

views:

486

answers:

5

how to get ip address of machine in c#

+1  A: 

First google result or another one

marcgg
+11  A: 
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

Your machine doesn't have a single IP address, and some of the returned addresses can be IPv6.

MSDN links:

Alternatively, as MSalters mentioned, 127.0.0.1 / ::1 is the loopback address and will always refer to the local machine. For obvious reasons, however, it cannot be used to connect to the local machine from a remote machine.

Richard Szalay
+1  A: 

This article shows everything.

Better if you can do a small research before asking a question.

Chathuranga Chandrasekara
+1  A: 
 IPHostEntry ip = DNS.GetHostByName (strHostName);
 IPAddress [] IPaddr = ip.AddressList;

 for (int i = 0; i < IPaddr.Length; i++)
 {
  Console.WriteLine ("IP Address {0}: {1} ", i, IPaddr[i].ToString ());
 }
Sri Kumar
GetHostByName is deprecated - http://msdn.microsoft.com/en-us/library/system.net.dns.gethostbyname.aspx
Richard Szalay
+2  A: 

My desired answer was

string ipAddress = "";
if (Dns.GetHostAddresses(Dns.GetHostName()).Length > 0)
{
     ipAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
}
Azhar
This is executing `GetHostAddresses` and `GetHostName` twice; you should assign the results of GetHostAddresses to a variable and then check the `Length`.
Richard Szalay
If you are looking for a more relevant IP address, you may want to exclude loopback IPs (e.g., 127.0.0.1 and ::1) with something like this: `.Where(ip => !Net.IPAddress.IsLoopback(ip))`.
patridge