Smart way to get the public Internet IP address/geo loc

12,774

Solution 1

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;
}

Solution 2

I prefer http://icanhazip.com. It returns a simple text string. No HTML parsing required.

string myIp = new WebClient().DownloadString(@"http://icanhazip.com").Trim();

Solution 3

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.

Solution 4

I believe you really need to connect with some server to get your external IP.

Solution 5

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.

Share:
12,774
Daniel Mošmondor
Author by

Daniel Mošmondor

http://my_blog.net http://www.formsnapper.net http://www.spotcontrol.com http://www.videophill.com http://sourceforge.net/projects/mpg123net/ I work hard for every 5 points here :) and will shamelessly try to forward traffic to my projects. [email protected]

Updated on June 04, 2022

Comments