如何从Python的ip范围列表中生成所有可能的IP

如何从Python的ip范围列表中生成所有可能的IP

本文介绍了如何从Python的ip范围列表中生成所有可能的IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含一堆ip范围的文本文件,如下所示:

Let's say I have a text file contains a bunch of ip ranges like this:

x.x.x.x-y.y.y.y
x.x.x.x-y.y.y.y
x.x.x.x-y.y.y.y
x.x.x.x-y.y.y.y
x.x.x.x-y.y.y.y

xxxx是起始值,yyyy是范围的结束值。

x.x.x.x is start value and y.y.y.y is end value of range.

如何在python的新文本文件中将这些ip范围转换为所有可能的IP?

How can I convert these ip ranges to all possible IPs in a new text file in python?

PS:这个问题与我以前的任何问题都不一样。我在前一个问题中问过如何从cidr符号生成所有可能的ips。但在这里我问如何从ip范围列表生成。这些是不同的东西。

PS: This question is not same as any of my previous questions. I asked "how to generate all possible ips from cidr notations" in my previous question. But in here I ask "how to generate from ip range list". These are different things.

推荐答案

此函数返回从开始到结束的所有IP地址:

This function returns all ip addresses like from start to end:

def ips(start, end):
    import socket, struct
    start = struct.unpack('>I', socket.inet_aton(start))[0]
    end = struct.unpack('>I', socket.inet_aton(end))[0]
    return [socket.inet_ntoa(struct.pack('>I', i)) for i in range(start, end)]

这些是建筑物阻止自己构建它:

These are the building blocks to build it on your own:

>>> import socket, struct
>>> ip = '0.0.0.5'
>>> i = struct.unpack('>I', socket.inet_aton(ip))[0]
>>> i
5
>>> i += 1
>>> socket.inet_ntoa(struct.pack('>I', i))
'0.0.0.6'

示例:

ips('1.2.3.4', '1.2.4.5')
['1.2.3.4', '1.2.3.5', '1.2.3.6', '1.2.3.7', ..., '1.2.3.253', '1.2.3.254', '1.2.3.255', '1.2.4.0', '1.2.4.1', '1.2.4.2', '1.2.4.3', '1.2.4.4']

从文件中读取

在您的情况下,您可以从以下文件中读取:

In your case you can read from a file like this:

with open('file') as f:
    for line in f:
        start, end = line.strip().split('-')
        # ....

这篇关于如何从Python的ip范围列表中生成所有可能的IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:18