从Windows应用程序获取IP地址位置
关于如何在asp.net中获取IP地址的地理位置,我在stackoverflow上看到了很多问题和答案,但是..
如何获取winforms中的IP地址位置?
我正在研究C#winform应用程序,我需要显示用户,它的IP地址和它的位置 。 我能够显示用户的本地,外部IP地址,但我找不到任何显示位置的方法。
任何机构都知道我是否可以使用任何WebRequest
或任何其他解决方案执行此操作?
编辑:我可以通过以下方法完成任务。
-
将IP地址发送到显示IP地址位置的站点。(例如www.whatismyipaddress.com)
-
获取其源代码。
-
解析其代码并使用
string
操作来获取位置。
但我知道这不是好方法,好像网站被关闭或移动或源代码中的任何更改将使我的代码无用。
IpInfo是与IP相关的很好的服务。 他们也有一个很好的API 。
在下面的代码中,我将向此服务发出Web请求,它将返回IP信息。
这将返回您的IP信息:
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; }
使用它的一个例子是:
Console.WriteLine (GetLocation("8.8.8.8"));
这将输出:
{ "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"}
您可以使用IP地址地理位置数据库
请享用
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