[英]How can I loop through an IP address range in python
How can I loop through an IP address range in python? 如何在python中遍历IP地址范围? Lets say I want to loop through every IP from 192.168.1.1 to 192.168.
让我们说我想遍历从192.168.1.1到192.168的每个IP。 How can this be done?
如何才能做到这一点?
If you want to loop through a network you can define a network using ipaddress module. 如果要循环通过网络,可以使用ipaddress模块定义网络。 Such as ipaddress.IPv4Network('192.168.1.0/24')
例如ipaddress.IPv4Network('192.168.1.0/24')
import ipaddress
for ip in ipaddress.IPv4Network('192.168.1.0/24'):
print(ip)
This will produce a result like this: 这将产生如下结果:
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
But if you want to iterate through a range of ip's, you might need to convert between ip and integer. 但是如果你想迭代一系列的ip,你可能需要在ip和integer之间进行转换。
>>> int(ipaddress.IPv4Address('10.0.0.1'))
167772161
So: 所以:
start_ip = ipaddress.IPv4Address('10.0.0.1')
end_ip = ipaddress.IPv4Address('10.0.0.5')
for ip_int in range(int(start_ip), int(end_ip)):
print(ipaddress.IPv4Address(ip_int))
will produce a result like: 会产生如下结果:
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
Did you try, you know, looping with range
? 你试过,你知道,你是否已经使用
range
循环了?
for i in range(256):
for j in range(256):
ip = "192.168.%d.%d" % (i, j)
print ip
You can use itertools.product
: 您可以使用
itertools.product
:
for i,j in product(range(256),range(256)):
print "192.168.{0}.{1}".format(i,j)
Using netaddr module: http://netaddr.readthedocs.io/en/latest/api.html#netaddr.IPSet.iter_ipranges 使用netaddr模块: http ://netaddr.readthedocs.io/en/latest/api.html#netaddr.IPSet.iter_ipranges
from netaddr import iter_iprange
generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)
generator.next() # 192.168.1.1
generator.next() # 192.168.1.2
from netaddr import *
ip = IPNetwork('192.0.2.16/29')
>>> ip_list = list(ip)
>>> len(ip_list)
8
>>> ip_list
[IPAddress('192.0.2.16'), IPAddress('192.0.2.17'), ..., IPAddress('192.0.2.22'), IPAddress('192.0.2.23')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.