获取公共互联网 IP 地址/地理位置的智能方法
我在本地网络上有一台计算机,位于 NAT 路由器后面。我有一些 192.168.0.x 地址,但我真的想知道我的公共 IP 地址,而不是
中提到的内容如何获取运行 C# 应用程序的服务器的 IP 地址?
或
我需要 C# 代码。
是否可以?如果是这样,怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我更喜欢http://icanhazip.com。它返回一个简单的文本字符串。无需 HTML 解析。
I prefer http://icanhazip.com. It returns a simple text string. No HTML parsing required.
经过一番搜索,并通过扩展我的要求,我发现这不仅会为我提供IP,而且还会为我提供地理位置:
返回XML,因此键/值字典将这样填充:
为了方便起见,返回班级:
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:
XML returned, and thus key/value dictionary will be filled as such:
And for convenience, return class:
问题是您要查找的 IP 地址不属于您的计算机。它属于您的 NAT 路由器。我能想到的唯一方法是使用外部服务器或通过某种方式查询路由器。
如果您的路由器支持 SNMP,您也许可以通过这种方式获取它。
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.
我相信你确实需要连接一些服务器来获取你的外部IP。
I believe you really need to connect with some server to get your external IP.
根据您使用的路由器,您很可能可以直接从路由器获取它。它们中的大多数都有一个 Web 界面,因此只需导航到正确的网页(例如“192.168.0.1/无论什么”)并从该页面“抓取”外部 IP 地址即可。当然,这样做的问题是它非常脆弱——如果您更改(甚至重新配置)路由器,它很可能会损坏。
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.
您也许可以使用 uPNP,如果失败,则可以回退到whatsmyip.com。
you may be able to use uPNP and fall-back to whatsmyip.com if that fails.
如果您担心连接丢失或站点的可用性,您也可以尝试通过包含上述建议来避免该问题。
希望这也能有所帮助。
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.
Hope this one also help.
我这样做:
我创建一个保存地理位置数据的类
,然后使用以下代码调用地理数据并填充该类。
由于答案是“坏”xml,因此需要指定 xRoot 元素,否则会出现错误。
快乐编码
沃尔特
I do it like this:
I create a class that holds the geo location data
then I use the following code to call the geo data and fill the class.
as the answer is "bad" xml one needs to specify the xRoot element or one gets an error.
Happy coding
Walter
下面的代码将帮助您获取公共IP地址
Below code will help you to take public IP address