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.
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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With