I have a computer on the local network, behind a NAT router. I have some 192.168.0.x addresses, but I really want to know my public IP address, not somethin
I believe you really need to connect with some server to get your external IP.
If you are worried about connection lose or the availability of the site, you can also try this way to avoid that issue by including above suggestions.
using System.Threading;
Task<string>[] tasks = new[]
{
Task<string>.Factory.StartNew( () => new System.Net.WebClient().DownloadString(@"http://icanhazip.com").Trim() ),
Task<string>.Factory.StartNew( () => new System.Net.WebClient().DownloadString(@"http://checkip.dyndns.org").Trim() )
};
int index = Task.WaitAny( tasks );
string ip = tasks[index].Result;
Hope this one also help.
you may be able to use uPNP and fall-back to whatsmyip.com if that fails.
I prefer http://icanhazip.com. It returns a simple text string. No HTML parsing required.
string myIp = new WebClient().DownloadString(@"http://icanhazip.com").Trim();
After some search, and by expanding my requirements, I found out that this will get me not only the IP, but GEO-location as well:
class GeoIp
{
static public GeoIpData GetMy()
{
string url = "http://freegeoip.net/xml/";
WebClient wc = new WebClient();
wc.Proxy = null;
MemoryStream ms = new MemoryStream(wc.DownloadData(url));
XmlTextReader rdr = new XmlTextReader(url);
XmlDocument doc = new XmlDocument();
ms.Position = 0;
doc.Load(ms);
ms.Dispose();
GeoIpData retval = new GeoIpData();
foreach (XmlElement el in doc.ChildNodes[1].ChildNodes)
{
retval.KeyValue.Add(el.Name, el.InnerText);
}
return retval;
}
}
XML returned, and thus key/value dictionary will be filled as such:
<Response>
<Ip>93.139.127.187</Ip>
<CountryCode>HR</CountryCode>
<CountryName>Croatia</CountryName>
<RegionCode>16</RegionCode>
<RegionName>Varazdinska</RegionName>
<City>Varazdinske Toplice</City>
<ZipCode/>
<Latitude>46.2092</Latitude>
<Longitude>16.4192</Longitude>
<MetroCode/>
</Response>
And for convenience, return class:
class GeoIpData
{
public GeoIpData()
{
KeyValue = new Dictionary<string, string>();
}
public Dictionary<string, string> KeyValue;
}
Depending on the router you use, chances are pretty good that you could get it directly from the router. Most of them have a web interface, so it would be a matter of navigating to the correct web page (e.g., "192.168.0.1/whatever") and "scraping" the external IP address from that page. The problem with this is, of course, that it's pretty fragile -- if you change (or even re-configure) your router, chances are pretty good that it'll break.