在 Python 中,如何确定 IP 地址是否是私有的?

2022-01-19 00:00:00 python ip-address network-programming

问题描述

在 Python 中,确定 IP 地址(例如,'127.0.0.1''10.98.76.6')是否在 私有网络?代码听起来并不难写.但是可能存在比立即明显更多的边缘情况,并且需要考虑 IPv6 支持等.是否有现有的库可以做到这一点?

In Python, what is the best way to determine if an IP address (e.g., '127.0.0.1' or '10.98.76.6') is on a private network? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?


解决方案

查看 IPy 模块.如果有一个函数 iptype() 似乎可以做你想做的事:

Check out the IPy module. If has a function iptype() that seems to do what you want:

>>> from IPy import IP
>>> ip = IP('127.0.0.0/30')
>>> ip.iptype()
'PRIVATE'

相关文章