簡體   English   中英

在python中按步驟給出IP地址時增加IP地址

[英]Increment an IP address when the IP address is given in steps in python

當我們有4 octets格式的 start_ip 和4 octets格式的步驟時,如何在 python 中增加 IP 地址。

假設我從 IP 地址225.1.1.1 ,步長為0.0.0.1當我說 next_ip = start_ip + step 時,它實際上應該評估 expand 產生的結果。 我知道ipaddr模塊僅通過添加就可以做到這一點,但是當該步驟也以 ipv4 格式給出時,這似乎不起作用。

執行此操作的任何已知步驟:

import ipaddr 
a = ipaddr.ipaddress('225.1.1.1')
b = a +1

這實際上返回了所需的結果。 但是當這樣遞增時:

b = a + 0.0.0.1 it does not seem to work.

任何已知的解決方案?

這段代碼可以添加兩個 4 個八位字節:

first = '192.168.0.4'
second = '0.0.0.1'
ipaddress.ip_address(first) + int(ipaddress.ip_address(second))

這將導致: IPv4Address('192.168.0.5')

沒有精煉,但我猜是有效的,這里是 python 片段

def increment_ip_addr(ip_addr):
    ip_arr = ip_addr.split('.')

    def increment_by_1(digit):
        return str(int(digit) + 1)

    if int(ip_arr[3]) > 254:
        ip_arr[3] = "1"
        if int(ip_arr[2]) > 254:
            ip_arr[2] = "1"
            if int(ip_arr[1]) > 254:
                ip_arr[1] = "1"
                if int(ip_arr[0]) > 254:
                    ip_arr[0] = "1"
                else:
                    ip_arr[0] = increment_by_1(ip_arr[0])
            else:
                ip_arr[1] = increment_by_1(ip_arr[1])
        else:
            ip_arr[2] = increment_by_1(ip_arr[2])
    else:
        ip_arr[3] = increment_by_1(ip_arr[3])
    print(f"for ip address: {ip_addr} The incremented ip is: {'.'.join(ip_arr)}")

[increment_ip_addr(ip_addr) for ip_addr in ['1.1.1.1', "1.1.1.255", "1.255.1.255", "255.255.255.255"]]

對應的控制台輸出:

for ip address: 1.1.1.1 The incremented ip is: 1.1.1.2
for ip address: 1.1.1.255 The incremented ip is: 1.1.2.1      
for ip address: 1.255.1.255 The incremented ip is: 1.255.2.1  
for ip address: 255.255.255.255 The incremented ip is: 1.1.1.1

如果有優化版本,請告訴我

暫無
暫無

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

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