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?
I just thought that I would add my own, one-liner (even though there are many other useful answers already).
string ipAddress = new WebClient().DownloadString("http://icanhazip.com");
The LINQ solution:
If you can't rely on getting your IP address from a DNS server (which has happened to me), you can use the following approach:
The System.Net.NetworkInformation namespace contains a NetworkInterface class, which has a static GetAllNetworkInterfaces method.
This method will return all "network interfaces" on your machine, and there are generally quite a few, even if you only have a wireless adapter and/or an ethernet adapter hardware installed on your machine. All of these network interfaces have valid IP addresses for your local machine, although you probably only want one.
If you're looking for one IP address, then you'll need to filter the list down until you can identify the right address. You will probably need to do some experimentation, but I had success with the following approach:
OperationalStatus == OperationalStatus.Up
. This will exclude your physical ethernet adapter, for instance, if you don't have a network cable plugged in.For each NetworkInterface, you can get an IPInterfaceProperties object using the GetIPProperties method, and from an IPInterfaceProperties object you can access the UnicastAddresses property for a list of UnicastIPAddressInformation objects.
DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
AddressPreferredLifetime != UInt32.MaxValue
.At this point I take the address of the first (if any) unicast address that matches all of these filters.
EDIT:
[revised code on May 16, 2018 to include the conditions mentioned in the text above for duplicate address detection state and preferred lifetime]
The sample below demonstrates filtering based on operational status, address family, excluding the loopback address (127.0.0.1), duplicate address detection state, and preferred lifetime.
Try this:
To find IP address list I have used this solution
But I personally like below solution to get local valid IP address