Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

ip-address

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?

like image 281
Nefzen Avatar asked Jul 01 '09 13:07

Nefzen


People also ask

How can I find the IP address of another computer?

How do I identify an unknown device on my network? To see all of the devices connected to your network, type arp -a in a Command Prompt window. This will show you the allocated IP addresses and the MAC addresses of all connected devices.

How do I find my IP address Windows C++?

You can use gethostname followed by gethostbyname to get your local interface internal IP. This returned IP may be different from your external IP though. To get your external IP you would have to communicate with an external server that will tell you what your external IP is.

How do I find the IP of a server name?

In an open command line, type ping followed by the hostname (for example, ping dotcom-monitor.com). and press Enter. The command line will show the IP address of the requested web resource in the response. An alternative way to call Command Prompt is the keyboard shortcut Win + R.


1 Answers

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.

like image 126
Andrew Hare Avatar answered Sep 22 '22 08:09

Andrew Hare