有人能想到一个算法将所有地址放在另外两个地址之间并将它们放在一个列表中(使用python)吗?例如:
findIPs('111.111.111.0', '111.111.111.3')
应该返回('111.111.111.0', '111.111.111.1', '111.111.111.2', '111.111.111.3')
。我的主要问题来自于相应的块是相同的,否则我可以使用带有范围函数的嵌套for循环。
答案 0 :(得分:11)
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'))
答案 1 :(得分:1)
这是一个非常简单的方法:
def ip_to_int(ip):
val = 0
for i, s in enumerate(ip.split('.')):
val += int(s) * 256 ** (3 - i)
return val
def int_to_ip(val):
octets = []
for i in range(4):
octets.append(str(val % 256))
val = val >> 8
return '.'.join(reversed(octets))
def findIPs(start, end):
for i in range(ip_to_int(start), ip_to_int(end) + 1):
yield int_to_ip(i)
示例:
>>> list(findIPs('111.111.111.0', '111.111.111.3'))
['111.111.111.0', '111.111.111.1', '111.111.111.2', '111.111.111.3']
>>> list(findIPs('111.111.111.254', '111.111.112.1'))
['111.111.111.254', '111.111.111.255', '111.111.112.0', '111.111.112.1']
答案 2 :(得分:0)
一点点搜索也可能找到答案,但这应该有效:
import socket
import struct
ip_to_number = lambda ip: struct.unpack('!I', socket.inet_aton(ip))[0]
number_to_ip = lambda num: socket.inet_ntoa(struct.pack('!I', num))
def ip_range(a, b):
a = ip_to_number(a)
b = ip_to_number(b)
for i in range(a, b+1):
yield number_to_ip(i)