Smart way to get the public Internet IP address/geo loc
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 something mentioned in
How开发者_运维问答 to get the IP address of the server on which my C# application is running on?
or
How to get the IP address of a machine in C#
I need C# code.
Is it possible? If so, how?
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;
}
The problem is that the IP address you're looking for doesn't belong to your computer. It belongs to your NAT router. The only ways I can think of getting it is to use an external server or have some way of querying your router.
If your router supports SNMP, you may be able to get it that way.
I believe you really need to connect with some server to get your external IP.
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.
you may be able to use uPNP and fall-back to whatsmyip.com if that fails.
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.
I do it like this: I create a class that holds the geo location data
[Serializable]
public class LocationData
{
public string IP { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
public string RegionCode { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string TimeZone { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string MetroCode { get; set; }
}
then I use the following code to call the geo data and fill the class.
public static LocationData GetLocation(string ip= "")
{
using (var client = new System.Net.WebClient())
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Response";
string downloadedString = client.DownloadString("http://freegeoip.net/xml/" + ip);
XmlSerializer mySerializer = new XmlSerializer(typeof(LocationData), xRoot) ;
using (XmlReader xmlReader = XmlReader.Create(new System.IO.StringReader(downloadedString)))
{
return mySerializer.Deserialize(xmlReader)as LocationData;
}
}
}
as the answer is "bad" xml one needs to specify the xRoot element or one gets an error.
Happy coding
Walter
Below code will help you to take public IP address
string _externalIP;
_externalIP = (new WebClient()).DownloadString("http://http://icanhazip.com/");
_externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
精彩评论