如何在python中遍历IP地址范围

Mic*_*ael 7 python

如何在python中遍历IP地址范围?让我们说我想遍历从192.168.1.1到192.168的每个IP.如何才能做到这一点?

小智 15

如果要循环通过网络,可以使用ipaddress模块​​定义网络.例如ipaddress.IPv4Network('192.168.1.0/24')

import ipaddress
for ip in ipaddress.IPv4Network('192.168.1.0/24'):
    print(ip)
Run Code Online (Sandbox Code Playgroud)

这将产生如下结果:

192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
...
192.168.1.255
Run Code Online (Sandbox Code Playgroud)

但是如果你想迭代一系列的ip,你可能需要在ip和integer之间进行转换.

>>> int(ipaddress.IPv4Address('10.0.0.1'))
167772161
Run Code Online (Sandbox Code Playgroud)

所以:

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))
Run Code Online (Sandbox Code Playgroud)

会产生如下结果:

10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 5

你知道,你试过循环range吗?

for i in range(256):
    for j in range(256):
        ip = "192.168.%d.%d" % (i, j)
        print ip
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 5

您可以使用itertools.product

for i,j in product(range(256),range(256)):
    print "192.168.{0}.{1}".format(i,j)
Run Code Online (Sandbox Code Playgroud)