在 Python 中,获取有关 IP 地址的更多信息
我了解 Python 中的 gethostbyaddr,这对我来说有点用处。我想获得有关 IP 地址的更多信息,就像人们可以在各种网站上找到的那样,例如谁托管该 IP 地址、原籍国等。我需要以编程方式完成此操作。
是否有适用于 Python 的内置命令,或者我需要访问包含此类信息的某个数据库,或者是否有任何 Python API? Python 不是我的母语,所以我不太熟悉如何在 Python 中解决这一问题。
I know about gethostbyaddr
in Python and that is somewhat useful for me. I would like to get even more info about an ip address like one can find at various websites such as who hosts that ip address, the country of origin, ..., etc. I need to accomplish this programmatically.
Are there any built in commands for Python, or would I need access to some database which contains this type of information, or are there any Python APIs? Python is not my native language so I am not as familiar with how one would approach such a problem in Python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 pywhois 检索 whois 信息,即托管组织/人员的名称和详细联系信息。请注意,whois 信息质量各不相同;通常,域名(使用
gethostbyaddr
找到)会比 IP 地址获得更好的结果。如果您只需要地理信息,请使用 pygeoip。它通过在数据库中查找 IP 地址来将其映射到某个位置,例如 MaxMind 提供的数据库。请注意,免费的“Lite”版本只能给您一个粗略的想法,20-50 公里的错误并不罕见。
You can use pywhois for retrieving whois information, i.e. name and contact details of the hosting organization/person. Note that whois information quality varies; usually, the domain name (found with
gethostbyaddr
) will get you way better results than the IP address.If you need only geographic information, use pygeoip. It maps an IP address to a location by looking it up in a database, such as the ones provided by MaxMind. Note that the free "Lite" versions will give you only a rough idea, and errors of 20-50km are not uncommon.
好的,这是我的答案。我将致力于清理我机器上的 Python 3.x 版本的 pywhois 以供公众使用,并希望在下周将我的代码提交到 subversion 存储库。从我使用的 IP 地址来看,我首先按照 phihag 的建议将 gethostbyaddr 应用于 IP 地址,然后通过 pywhois 进行检索,成功率约为 78%。我将让读者自己决定该速率对于他们的特定应用程序是否足够高。
Ok, here is my answer. I am going to work on cleaning up for public consumption a Python 3.x version of pywhois that I have on my machine and hopefully in the next week I will submit my code to the subversion repository. From the IP addresses I am using, I have about a 78% success rate for retrieving info first by applying gethostbyaddr to the IP address as phihag suggested and then putting that through pywhois. I will let the reader decide for themselves whether that rate is high enough for their particular application.