python 查找ip段之間的所有ip

方法一

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'))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章