简体   繁体   English

在python中按步骤给出IP地址时增加IP地址

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

How do I increment the IP address in python when we have start_ip in 4 octets format and the step also in 4 octet format.当我们有4 octets格式的 start_ip 和4 octets格式的步骤时,如何在 python 中增加 IP 地址。

Let's suppose I start with an IP address of 225.1.1.1 , and the step as 0.0.0.1 When I say next_ip = start_ip + step, it should actually evaluate the expand produce the result.假设我从 IP 地址225.1.1.1 ,步长为0.0.0.1当我说 next_ip = start_ip + step 时,它实际上应该评估 expand 产生的结果。 I know that the ipaddr module does this with just an addition, but that does not seem to work when the step is also given in the ipv4 format.我知道ipaddr模块仅通过添加就可以做到这一点,但是当该步骤也以 ipv4 格式给出时,这似乎不起作用。

Any known steps to do this:执行此操作的任何已知步骤:

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

This actually returns the desired result.这实际上返回了所需的结果。 but when increment like this:但是当这样递增时:

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

Any known solutions for this?任何已知的解决方案?

this piece of code can add two 4 octets :这段代码可以添加两个 4 个八位字节:

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

this will result in: IPv4Address('192.168.0.5')这将导致: IPv4Address('192.168.0.5')

Not refined but works i guess, here is the python snippet没有精炼,但我猜是有效的,这里是 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"]]

corresponding console output:对应的控制台输出:

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

Let me know in case of optimized version如果有优化版本,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM