使用python从特定ip地址获取ip范围

使用python从特定ip地址获取ip范围,python,python-2.7,Python,Python 2.7,嗨,我在为ip地址编写python程序时遇到了一个问题。 计划是:- ip1='192.168.0.0' ip2='192.168.255.255' ip1=ip1.split('.') ip2=ip2.split('.') while ip1[2]<=ip2[2]: print ip1[0]+'.'+ip1[1]+'.'+ip1[2]+'.'+ip1[3] ip1[2]=ip1[2]+1 while ip1[3]<=ip2[3]: print ip1[0]+

嗨,我在为ip地址编写python程序时遇到了一个问题。 计划是:-

ip1='192.168.0.0'
ip2='192.168.255.255'
ip1=ip1.split('.')
ip2=ip2.split('.')
while ip1[2]<=ip2[2]:
    print ip1[0]+'.'+ip1[1]+'.'+ip1[2]+'.'+ip1[3]
    ip1[2]=ip1[2]+1
while ip1[3]<=ip2[3]:
    print ip1[0]+'.'+ip1[1]+'.'+ip1[2]+'.'+ip1[3]
    ip1[3]=ip1[3]+1
ip1='192.168.0.0'
ip2='192.168.255.255'
ip1=ip1。拆分('.'))
ip2=ip2。拆分('.'))
而ip1[2]就这样使用

for i in range(256):
    for j in range(256):
        ip = "192.168.%d.%d" % (i, j)
        print ip
输出:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
.
.
192.168.255.254
192.168.255.255
就这样用吧

for i in range(256):
    for j in range(256):
        ip = "192.168.%d.%d" % (i, j)
        print ip
输出:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
.
.
192.168.255.254
192.168.255.255

您可以使用Python中内置的
ipaddress
()模块:

import ipaddress

for address in ipaddress.ip_network('192.168.0.0/16'):
    print(address)
印刷品:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3

...all the way to:

192.168.255.252
192.168.255.253
192.168.255.254
192.168.255.255

您可以使用Python中内置的
ipaddress
()模块:

import ipaddress

for address in ipaddress.ip_network('192.168.0.0/16'):
    print(address)
印刷品:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3

...all the way to:

192.168.255.252
192.168.255.253
192.168.255.254
192.168.255.255

使用IP地址模块。您可以轻松检查ip范围。(范围从nip1到nip2)


使用IP地址模块。您可以轻松检查ip范围。(范围从nip1到nip2)


如果希望IP地址范围是动态的,可以执行以下操作:

ip1='192.168.0.0'
ip2='192.168.255.255'

first, second, thirdStart, lastStart = list(map(int,ip1.split(".")))
thirdEnd, lastEnd = list(map(int,ip2.split(".")))[2:] 

for i in range(thirdStart,thirdEnd+1,1):
    for j in range(lastStart,lastEnd+1,1):
        print(".".join(list(map(str,[first,second,i,j]))))
输出:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
.
.
.
192.168.255.252
192.168.255.253
192.168.255.254
192.168.255.255

如果希望IP地址范围是动态的,可以执行以下操作:

ip1='192.168.0.0'
ip2='192.168.255.255'

first, second, thirdStart, lastStart = list(map(int,ip1.split(".")))
thirdEnd, lastEnd = list(map(int,ip2.split(".")))[2:] 

for i in range(thirdStart,thirdEnd+1,1):
    for j in range(lastStart,lastEnd+1,1):
        print(".".join(list(map(str,[first,second,i,j]))))
输出:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
.
.
.
192.168.255.252
192.168.255.253
192.168.255.254
192.168.255.255

我不知道有这样的库,期望python不会少:)我不知道有这样的库,期望python不会少:)