简体   繁体   中英

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.

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. 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.

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 :

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')

Not refined but works i guess, here is the python snippet

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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