Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python increment ipaddress

I would like to increment an ip address by a fixed value.

Precisely this is what I am trying to achieve, I have an ip address say, 192.168.0.3 and I want to increment it by 1 which would result in 192.168.0.4 or even by a fixed value, x so that it will increment my ip address by that number. so, I can have a host like 192.168.0.3+x.

I just want to know if any modules already exist for this conversion.

I tried socket.inet_aton and then socket.inet_ntoa, but I don't know how to get that working properly. Need some help or advice on that.

like image 809
sabs6488 Avatar asked Mar 02 '12 19:03

sabs6488


People also ask

How do you increment an IP address?

To increment an IP address you will need to break up the in_addr object into 4 int objects (a short int will also do) and increment the 4th one until it hits 256, and then reset it to 1 and increment the 3rd one, etc. You shouldn't be using ++ on the in_addr object directly.


1 Answers

In Python 3:

>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.4')  # accept both IPv4 and IPv6 addresses
IPv4Address('192.168.0.4')
>>> int(_)
3232235524

>>> ipaddress.ip_address('192.168.0.4') + 256
IPv4Address('192.168.1.4')

In reverse:

>>> ipaddress.ip_address(3232235524)
IPv4Address('192.168.0.4')
>>> str(_)
'192.168.0.4'

>>> ipaddress.ip_address('192.168.0.4') -1
IPv4Address('192.168.0.3')

Python 2/3

You could use struct module to unpack the result of inet_aton() e.g.,

import struct, socket

# x.x.x.x string -> integer
ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]
print(ip2int("192.168.0.4"))
# -> 3232235524

In reverse:

int2ip = lambda n: socket.inet_ntoa(struct.pack('!I', n))
print(int2ip(3232235525))
# -> 192.168.0.5
like image 138
jfs Avatar answered Sep 27 '22 21:09

jfs