Search code examples
c#.netgeolocationip-address

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?


Solution

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