Python-根据起始IP创建IP列表

时间:2018-08-06 21:18:00

标签: python networking ip-address

我花了几个小时研究,这让我很困惑。在走新路之前,我正在寻找最佳实践。

基于列表中的项目数量,最终我需要一个IP列表( 就是这些IP)。

我一直在使用ipaddress模块;这是我所得到的最近的东西。

import ipaddress
IP_Start = 192.168.1.1
hostnames = [hostname1, hostname2, hostname3]
list_of_ips = []
my_range = range(len(hostnames))
for ips in my_range:
    list_of_ips.append(ipaddress.ip_address(IP_Start) + my_range[ips])
print(list_of_ips)

输出:

list_of_ips = [IPv4Address('192.168.1.1'), IPv4Address('192.168.1.2'), IPv4Address('192.168.1.3')]

由于某种原因,我无法从字符串列表中剥离“ IPv4Address('')”;我的输出可能不是传统列表。使用str.replace时,我会遇到奇怪的错误,并且认为replac的出现可能不是最佳做法。

我觉得如果放弃ipaddress模块,将会有一种更简单的方法。这样做会是更好的方法,所以我的输出很简单

list_of_ips = [192.168.1.1, 192.168.1.2, 192.168.1.3]

2 个答案:

答案 0 :(得分:1)

IPv4Address是返回对象的数据类型。那是一个班级的名字。该类的显示函数表示它返回您看到的格式,其中IP地址为字符串。您需要查找该类,以找到一种方法(函数)或属性(数据字段)来为您提供IP地址作为字符串,而其余对象则不会随之标记。

最简单的方法是将其转换为str

for ips in my_range:
    list_of_ips.append(str(ipaddress.ip_address(IP_Start)) ... )

答案 1 :(得分:0)

这是仅使用内置函数的方法

从将IP地址转换为长整数的功能开始,然后是将长整数转换回IP地址的另一功能

import socket,struct
def ip_to_int(ip_address):
    return struct.unpack('!I', socket.inet_aton(ip_address))[0]


def int_to_ip(int_value):
    return socket.inet_ntoa(struct.pack('!I', int_value))

那么您要做的就是遍历您的范围

def iter_ip_range(start_address, end_address):
    for i in range(ip_to_int(start_address), ip_to_int(end_address) + 1):
        yield int_to_ip(i)

并使用它

print(list(iter_ip_range("192.168.11.12","192.168.11.22")))