jat*_*ism 35
如果您没有使用内置模块,那么有一个名为netaddr的项目是我用于处理IP网络的最佳模块.
看看IP教程,它说明了它如何轻松地与网络一起工作并辨别其IP.简单的例子:
>>> from netaddr import IPNetwork
>>> for ip in IPNetwork('192.0.2.0/23'):
... print '%s' % ip
...
192.0.2.0
192.0.2.1
192.0.2.2
192.0.2.3
...
192.0.3.252
192.0.3.253
192.0.3.254
192.0.3.255
Run Code Online (Sandbox Code Playgroud)
Pet*_*rik 17
在Python 3中就像
>>> import ipaddress
>>> [str(ip) for ip in ipaddress.IPv4Network('192.0.2.0/28')]
['192.0.2.0', '192.0.2.1', '192.0.2.2',
'192.0.2.3', '192.0.2.4', '192.0.2.5',
'192.0.2.6', '192.0.2.7', '192.0.2.8',
'192.0.2.9', '192.0.2.10', '192.0.2.11',
'192.0.2.12', '192.0.2.13', '192.0.2.14',
'192.0.2.15']
Run Code Online (Sandbox Code Playgroud)
我宁愿做一些数学而不是安装一个外部模块,没有人和我有同样的味道?
#!/usr/bin/env python
# python cidr.py 192.168.1.1/24
import sys, struct, socket
(ip, cidr) = sys.argv[1].split('/')
cidr = int(cidr)
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)
# excludes the first and last address in the subnet
for i in range(start, end):
print(socket.inet_ntoa(struct.pack('>I',i)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31317 次 |
| 最近记录: |