Smart way to get the public Internet IP address/geo loc(获取公共 Internet IP 地址/地理位置的智能方法)
问题描述
我在本地网络上有一台计算机,位于 NAT 路由器后面.我有一些 192.168.0.x 地址,但我真的很想知道我的公共 IP 地址,而不是
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
如何获取运行我的 C# 应用程序的服务器的 IP 地址?
或
如何在C#中获取机器的IP地址
我需要 C# 代码.
有可能吗?如果有,怎么做?
Is it possible? If so, how?
推荐答案
经过一番搜索,通过扩展我的需求,我发现这不仅可以获得 IP,还可以获得 GEO-location:
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,因此键/值字典将按如下方式填充:
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>
为了方便,返回类:
class GeoIpData
{
public GeoIpData()
{
KeyValue = new Dictionary<string, string>();
}
public Dictionary<string, string> KeyValue;
}
这篇关于获取公共 Internet IP 地址/地理位置的智能方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取公共 Internet IP 地址/地理位置的智能方法
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
