3

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?

Community
  • 1
  • 1
Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
  • 7
    Get your external IP without relying on public servers? Why? You do realize that your "external" IP to some degree *always* relies on the public Internet? – bzlm Feb 02 '11 at 21:05
  • http://msdn.microsoft.com/en-us/library/system.net.webrequest.getsystemwebproxy.aspx Might help – CodingBarfield Feb 02 '11 at 21:09
  • 2
    Easiest way "cheating": open http://www.whatismyip.com/ with a `WebClient` and parse the output to get your IP address – BrokenGlass Feb 02 '11 at 21:23
  • I removed the requirement for not using external server to stop flaming me down... – Daniel Mošmondor Feb 02 '11 at 21:24
  • whatismyip.com has an automation page for scripts and programs to use that just returns the IP address so you don't need to screen scrape. The URL is linked from here: http://www.whatismyip.com/automation/ – indiv Feb 03 '11 at 03:43
  • possible duplicate of [How to get my own IP address in C#?](http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c) – Oleg V. Volkov Jul 26 '12 at 18:18

9 Answers9

24

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

string myIp = new WebClient().DownloadString(@"http://icanhazip.com").Trim();
Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
6

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;
}
Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
5

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.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
2

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

methyl
  • 3,272
  • 2
  • 25
  • 34
2

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

you may be able to use uPNP and fall-back to whatsmyip.com if that fails.

Bengie
  • 1,035
  • 5
  • 10
0

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.

Nithin Paul
  • 2,169
  • 3
  • 33
  • 55
0

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

0

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();
Anjan Kant
  • 4,090
  • 41
  • 39