將 IP 范圍 10.10.10.1-10.10.10.10 轉為列表,供 for 循環遍歷使用。
ips = []
for i in range(1, 11): # Python 3 使用 range,Python 2 用 xrange
ips.append("10.10.10.%d" % i)
print(ips)
# 輸出: ['10.10.10.1', '10.10.10.2', ..., '10.10.10.10']
def ip_range(start_ip, end_ip):
"""生成 IP 范圍列表,假設前三段相同,僅最后一段變化"""
prefix = '.'.join(start_ip.split('.')[:3])
start = int(start_ip.split('.')[-1])
end = int(end_ip.split('.')[-1])
return [f"{prefix}.{i}" for i in range(start, end + 1)]
# 使用示例
print(ip_range("10.10.10.1", "10.10.10.10"))
xrange 節省內存,Python 3 range 已是惰性序列。ipaddress 標準庫(Python 3.3+)。