将IP列表与另一个IP列表或IP范围进行比较

时间:2016-10-21 20:45:17

标签: python list networking ip-address python-3.5

我创建了一个扫描ip范围(即x.y.z.0 / 24)的python项目,并返回一个在线主机列表。它只使用ip保存在线主机列表(即[' 192.168.0.1',' 192.168.0.2',' 192.168.0.8) ',...]。我在下一步遇到了问题。我想将这个在线主机列表与IP范围进行比较,以验证这些是用于消除其他设备的计算机。我有一个我可以使用的计算机的DHCP保留列表。有一个简单的方法来执行此操作并更新onHosts列表吗?

1 个答案:

答案 0 :(得分:1)

这是你可以尝试的建议解决方案(它有点臃肿但我希望以后编辑它)

def get_range(str_num):
    """ Converts string representation of number or range into (min,max) tuple """
    try:
        num = int(str_num)
        return num, num
    except ValueError:
        min_, max_ = str_num.split('-')
        return int(min_), int(max_)

def host_in_range(host, host_range):
    """ Checks whether given host belongs to given range (both are range representation """
    #print(*zip(host, host_range))
    for (min_h, max_h), (min_r, max_r) in zip(host, host_range):
        if (min_h < min_r) or (max_h > max_r): return False
    return True


if __name__ == "__main__":

    hosts_str = ['192.168.0.1', '192.168.0.10', '0.168.0.0', '192.168.1.10', '192.168.0.255']
    hosts = [x.split('.') for x in hosts_str]
    hosts = [[get_range(x) for x in elem] for elem in hosts]

    host_ranges_str = ['0-255.168.0.0-254', '192.168.2-5.0-255']
    host_ranges = [x.split('.') for x in host_ranges_str]
    host_ranges = [[get_range(x) for x in elem] for elem in host_ranges]

    for x in range(5):
        print(hosts_str[x], "in range", host_ranges_str[0], host_in_range(hosts[x], host_ranges[0]))