If you try to find the IP address your machine is using, you can follow two paths. The most obvious one is:
string host = System.Net.Dns.GetHostName();
System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(host);
System.Net.IPAddress addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
if (addr[i].AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
Unfortunately, in most cases, people are connected to the internet through a router, and therefore each machine is assigned with an internal IP
address of the private LAN network, assigning the external IP address to the router only, not to each machine. Finding this external address directly is not trivial, as you would need to deal with the router itself, with different router models, etc.
The easiest way to find the external IP
address is to do a web request to one of the several websites out there specially designed to provide you with that address, like whatismyipaddress.com, www.whatismyip.com, etc. In this case, we will use the last one.
Of course, doing a web request can take time, specially if there is no internet connection available, as the default timeout can take several seconds. This function will do the job for you,
and accept a custom timeout:
It works pretty obviously. It just uses the
DownloadDataAsync method, instead of the synchronous
DownloadData, and waits for a certain amount of time.
If no response is received in that time, it cancels the async method and returns null.
Hope it helps!