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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With