Python 计算两个IP段之间的有效IP地址

Can anyone think of an algorithm to put all of the addresses between two others and put them in a list (using python)? For example:

findIPs('111.111.111.0', '111.111.111.3')

Should return ('111.111.111.0', '111.111.111.1', '111.111.111.2', '111.111.111.3'). My main problem arises from when corresponding blocks are identical otherwise I could just use nested for loops with the range function

方法一:

try:
    from ipaddress import ip_address
except ImportError:
    from ipaddr import IPAddress as ip_address

def findIPs(start, end):
    start = ip_address(start)
    end = ip_address(end)
    result = []
    while start <= end:
        result.append(str(start))
        start += 1
    return result

print(findIPs('111.111.111.0', '111.111.111.3'))

打印结果:

方法二:

import struct
import socket

def findIPs(start, end):
    ipstruct = struct.Struct('>I')
    start, = ipstruct.unpack(socket.inet_aton(start))
    end, = ipstruct.unpack(socket.inet_aton(end))
    return [socket.inet_ntoa(ipstruct.pack(i)) for i in range(start, end+1)]

print(findIPs('111.111.111.0', '111.111.111.3'))

 

 原文地址:https://stackoverflow.com/questions/17220308/how-to-find-all-ip-addresses-between-2-ip-addresses

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值