I have seen many questions and answer on stackoverflow regarding how to fetch geolocation of an IP address in asp.net but..
How can I fetch the IP address location in winforms ?
I am working on the C# winform application and I need to show user ,its ip address and Its location.
I am able to show user's Local,External IP address but I could not find any way to show Location.
Any body knows if I can do this with any WebRequest
or any other solution ?
Edit: I am able to accomplish the task by following method.
Send IP address to a site which shows location from the IP address.(e.g. www.whatismyipaddress.com)
fetching its source code.
parsing its code and use string
operations to get the location.
But I know It is not good approach as if website is down or moved or any change in the source code will make my code useless.
IpInfo is nice service for IP related things. They also have a nice API.
In the code below, I will make a web request to this service and it will return the IP info.
This will return your IP info:
public static string GetLocation(string ip)
{
var res = "";
WebRequest request = WebRequest.Create("http://ipinfo.io/" + ip);
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string line;
while ((line = stream.ReadLine()) != null)
{
res += line;
}
}
return res;
}
An example using this is:
Console.WriteLine (GetLocation("8.8.8.8"));
This will output:
{ "ip": "8.8.8.8", "hostname": "No Hostname", "city": "Mountain View", "region": "California", "country": "US", "loc": "37.3860,-122.0838", "org": "AS15169 Google Inc.", "postal": "94035"}
You can use IP address geolocation database
Enjoy
For querying GeoIP information about your own IP:
http://ip-json.rhcloud.com/json
http://ip-json.rhcloud.com/xml
http://ip-json.rhcloud.com/csv
For querying GeoIP information about IP address:
http://ip-json.rhcloud.com/json/64.27.57.24
http://ip-json.rhcloud.com/xml/64.27.57.24
http://ip-json.rhcloud.com/csv/64.27.57.24
For querying GeoIP information about a domain:
http://ip-json.rhcloud.com/json/www.google.com
http://ip-json.rhcloud.com/xml/www.google.com
http://ip-json.rhcloud.com/csv/www.google.com
You can use curl command in terminal:
curl ip-json.rhcloud.com
curl ip-json.rhcloud.com/ua
curl ip-json.rhcloud.com/all
curl ip-json.rhcloud.com/json
curl ip-json.rhcloud.com/xml