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?
Here is how i solved it. i know if you have several physical interfaces this might not select the exact eth you want.
If you want to avoid using DNS:
Maybe by external IP you can consider (if you are in a Web server context) using this
I was asking the same question as you and I found it in this stackoverflow article.
It worked for me.
If you are running in intranet you'll be able to get local machine IP address and if not you'll get external ip address with this: Web:
Desktop: