Fork me on GitHub

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('', '')

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


    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:
        start += 1
    return result

print(findIPs('', ''))



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('', ''))



********************* 交流即分享,分享才能进步! 不对之处,还请各位前辈多多指教。 by 星云 ********************
posted @ 2018-05-17 09:34  星云博客园  阅读(3535)  评论(0编辑  收藏  举报