<p>一种方法是将IP地址转换回一个数字,然后计数,直到使用了整个数字范围。这也适用于<code>10.0.1.250-10.0.2.5</code></p>
<pre><code>import socket
import struct
ip_addresses = []
with open("test5.txt") as f_input:
for line in f_input:
if line.startswith('IP:'):
for entry in line.split(':')[1].split(','):
ip_range = entry.split('-', 1)
if len(ip_range) == 2:
start_ip = struct.unpack('>L', socket.inet_aton(ip_range[0].replace('-', '.')))[0]
end_ip = struct.unpack('>L', socket.inet_aton(ip_range[1].replace('-', '.')))[0]
while start_ip <= end_ip:
ip_addresses.append(socket.inet_ntoa(struct.pack('>L', start_ip)))
start_ip += 1
else:
ip_addresses.append(ip_range[0])
print ip_addresses
</code></pre>
<p>因此,如果<code>test5.txt</code>包含:</p>
^{pr2}$
<p>您将得到以下输出:</p>
^{3}$
<p><a href="https://docs.python.org/2/library/socket.html?highlight=ntoa#socket.inet_ntoa" rel="nofollow noreferrer">^{<cd3>}</a>接受字符串格式的IP地址并将其转换为二进制格式。<a href="https://docs.python.org/2/library/struct.html?highlight=struct.unpack#struct.unpack" rel="nofollow noreferrer">^{<cd4>}</a>接受压缩二进制格式的数字并将其转换为数字,例如<code>0.0.0.1</code>将转换为<code>1</code>。然后,脚本只需正常计数,直到到达结束编号,每次都要反向转换,以字符串格式重新创建IP地址。在</p>