使用Python从特定的IP地址获取IP范围

时间:2018-08-10 06:27:36

标签: 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]+'.'+ip1[1]+'.'+ip1[2]+'.'+ip1[3]
    ip1[3]=ip1[3]+1

该程序仅给我一个结果:-192.168.0.0 预期的答案是:-

    192.168.0.0
    192.168.0.1
    192.168.0.2
    ......
    192.168.255.255

4 个答案:

答案 0 :(得分:3)

您可以使用Python内置的ipaddressdocs here)模块:

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

答案 1 :(得分:1)

只是这样使用。

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

答案 2 :(得分:0)

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

import ipaddress

ip1='192.168.0.0'
ip2='192.168.255.255'


nip1 = int(ipaddress.IPv4Address(ip1))
nip2 = int(ipaddress.IPv4Address(ip2))

for n in range(nip1, nip2+1):
    add=str(ipaddress.IPv4Address(n))
    print(add)

答案 3 :(得分:0)

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

fdisk -l:

Disk /dev/sdb: 34.1 MiB, 35717120 bytes, 69760 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x158da426
Device     Boot Start   End Sectors  Size Id Type
/dev/sdb1        2048 69759   67712 33.1M 83 Linux

Disk /dev/mapper/ceph--a2fd39c4--7f95--4597--8458--beb4002f6553-osd--block--27355775--b236--4f96--9225--9625754d54a6: 32 MiB, 33554432 bytes, 65536 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

root@node1:~# ceph -s
   cluster:
    id:     649c70f4-b0f1-4c3d-baa8-672f5fbb9342
    health: HEALTH_OK

  services:
    mon: 1 daemons, quorum node1
    mgr: node1(active)
    osd: 13 osds: 0 up, 0 in

  data:
    pools:   0 pools, 0 pgs
    objects: 0  objects, 0 B
    usage:   0 B used, 0 B / 0 B avail
    pgs:

输出:

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]))))