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 wan
It might be quicker to just use simple addition and iteration, something like:
ip = [192,168,0,0]
ip_dict = {}
ip_list = []
for i in range(100):
new_ip = ip[3]+=1
ip_dict[i]=new_ip
ip_list.append(new_ip)
The library ipcalc has routines to make math on ip addresses fairly easy. As an example an iterator for an address range can be done like:
Code:
import ipcalc
network = ipcalc.Network('10.1.0.0/16')
host_first = network.host_first()
addresses = (host_first + i for i in range(network.size()-2))
Test Code:
print(next(addresses))
print(next(addresses))
print(next(addresses))
print(max(list(addresses)))
Results:
10.1.0.1
10.1.0.2
10.1.0.3
10.1.255.254
EDIT: This is buggy and shouldn't be used as is.
I would use ipaddr for this
>>> import ipaddr
>>> a = ipaddr.IPAddress('192.168.0.3')
>>> a
IPv4Address('192.168.0.3')
>>> a + 1
IPv4Address('192.168.0.4')
Convert the last part of your IP address into a number, add 1 to it, and call ifconfig
.
I think the approach of incrementing the last bit will not scale well as we span across networks. –OP
I thought of mentioning that in my original answer, but didn't, for various reasons. These reasons are as follows:
def FunIncrementIp(IPADDRESS,IPADDRESSES):
#import the ipaddress module and also check whether it is an ipv6 or ipv4
import ipaddress
if ':' in IPADDRESS:
IPADDRESSMOD = ipaddress.IPv6Address(IPADDRESS)
print ('this is ipv6 address')
else:
IPADDRESSMOD = ipaddress.IPv4Address(IPADDRESS)
print ('this is ipv4 address')
IPADDRESSES = int(c)
IPADDRESSES = IPADDRESSMOD+IPADDRESSES
while IPADDRESSMOD < IPADDRESSES:
IPADDRESSMOD += 1
print(IPADDRESSMOD)
This should do it.
FunIncrementIp('1.1.1.1','10')
This will increment your ipv4 addresses to 10 more
FunIncrementIp('2001:db8:0:1:1:1:1:1','10')
This will increment your ipv6 addresses to 10 more This will also tell auto detect the type of ip address so that you don't have to have separate script for ipv4 & ipv6.
From python 3.4 onwards:
>>> import ipaddress
>>> a = ipaddress.IPv4Address('192.168.0.1')
>>> a+500
IPv4Address('192.168.1.245')
>>> a = ipaddress.IPv6Address('2001:1900:2254:206a::50:0')
>>> a+200
IPv6Address('2001:1900:2254:206a::50:c8')
>>>