how to get ip address of machine in c#
+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
2010-01-07 10:00:56
+1
A:
This article shows everything.
Better if you can do a small research before asking a question.
Chathuranga Chandrasekara
2010-01-07 10:00:57
+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
2010-01-07 10:02:11
GetHostByName is deprecated - http://msdn.microsoft.com/en-us/library/system.net.dns.gethostbyname.aspx
Richard Szalay
2010-01-07 10:04:04
+2
A:
My desired answer was
string ipAddress = "";
if (Dns.GetHostAddresses(Dns.GetHostName()).Length > 0)
{
ipAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
}
Azhar
2010-01-07 10:35:12
This is executing `GetHostAddresses` and `GetHostName` twice; you should assign the results of GetHostAddresses to a variable and then check the `Length`.
Richard Szalay
2010-01-11 10:26:50
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
2010-03-15 17:12:23