簡體   English   中英

在python中查找下一個可用的IP地址

[英]Find next available IP address in python

在使用python的情況下,我需要根據給定的IP地址范圍找到下一個IP地址。 因此,如果我有一個IP地址列表,例如...

IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']

當我要求下一個IP地址時,我需要它返回“ 10.220.1.4”。 下一個請求將返回“ 10.220.1.6”,依此類推。

如果您使用的是Python 3.3(或更高版本),則可以使用ipaddress模塊。 子網10.220.1.0/24所有主機的示例,但reserved中的主機除外:

from ipaddress import IPv4Network

network = IPv4Network('10.220.1.0/24')
reserved = {'10.220.1.1', '10.220.1.2', '10.220.1.3', '10.220.1.5'}

hosts_iterator = (host for host in network.hosts() if str(host) not in reserved)

# Using hosts_iterator:
print(next(hosts_iterator))  # prints 10.220.1.4
print(next(hosts_iterator))  # prints 10.220.1.6
print(next(hosts_iterator))  # prints 10.220.1.7

# Or you can iterate over hosts_iterator:
for host in hosts_iterator:
    print(host)

因此,基本上,這可以在一行中完成(+導入以及網絡和保留地址的定義)。

您可以使用ipaddress模塊使用生成器,該模塊是python> = 3.3的補充,或者可以與pip一起安裝以用於早期版本:

In [20]: from ipaddress import ip_network

In [21]: IPs = {'10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5'}

In [22]: net = ip_network(u"10.220.1.0/24")

In [23]: avail =(str(ip) for ip in net.hosts() if str(ip) not in IPs
   ....: )

In [24]: next(avail)
Out[24]: '10.220.1.4'

In [25]: next(avail)
Out[25]: '10.220.1.6'

如果您使用的是Python 3,則可以將ipaddress與generator一起使用:

import ipaddress

def gen_ip(start, reserved):
    start = int(ipaddress.IPv4Address(start))
    for i in range(start + 1, int(2 ** 32) + 1):
        ip = str(ipaddress.IPv4Address(i))
        if ip not in reserved:
            yield ip

IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
j = 0
for ip in gen_ip(min(IPs), set(IPs)):
    print(ip)
    j += 1
    if j == 5:
        break

輸出:

10.220.1.4
10.220.1.6
10.220.1.7
10.220.1.8
10.220.1.9

創建一個基本的ip對象來保存當前ip的記錄並獲取下一個ip

class IPObj(object):
    def __init__(self, list_of_ips):
        self.position = 0
        self.ips = list_of_ips
        self.current_ip = self.ips[self.position]

    def next_ip(self, stop_iteration=False):
        '''
            return the next ip in the list
            '''

        if self.position >= len(self.ips)-1:
            self.position = 0 # By default next_ip will do nothing when it reaches the end but it will throw an exception if stop_iteration==True
            if stop_iteration:
                raise StopIteration
        self.position += 1
        self.current_ip = self.ips[self.position]
        return self.current_ip

    def __repr__(self):
        return repr(self.current_ip)


#Testing    
ips = IPObj(['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5'])

print ips

while True:
    print ips.next_ip(True),

輸出:10.220.1.1、10.220.1.2、10.220.1.3、10.220.1.5,

追溯(最近一次通話):

文件“ C:\\ Users \\ J10ey \\ workspace \\ SO_Help \\ src \\ ip's.py”(打印)ips.next_ip(True)文件“ C:\\ Users \\ J10ey \\ workspace \\ SO_Help \\ src \\ ip's.py”第21行,在next_ip中,引發StopIteration StopIteration

將您的列表轉換為一組,以提高性能:

used_ips = set(IPs)

現在根據需要生成IP#,並檢查它們是否包含在集合中:

for next_ip in generate_ip_numbers():
    if next_ip in used_ips:
        continue

    print("Next ip address is:", next_ip)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM