Calculate the other IP of a /31 IP address with python

111 Views Asked by At

I'm trying to build a 'neighbour IP converter' for a point to point IP subnet in python

i.e.

ip_A = '192.168.70.70/31
ip_A_neigh = '192.168.70.71'

ip_B = '10.10.89.5/31
ip_B_neigh = '10.10.89.4'

I've been looking at ipaddress and iptools python modules but I'm still trying to find my way with python...

I suppose I can split and if the last octet is an even number, add by 1 If the last octet is an odd number, reduce it by 1.

Is there a better way?

1

There are 1 best solutions below

1
Kiattisak Jantasri On

Use ipaddress module. already build-in python3 https://docs.python.org/3/library/ipaddress.html

import ipaddress

ip1 = "1.1.1.1/31"
net4 = ipaddress.ip_network(ip1, strict=False)
iface = ipaddress.ip_interface(ip1)
next_hop = ""
if iface.ip == net4[0]:
    next_hop = net4[1]
elif iface.ip == net4[1]:
    next_hop = net4[0]


#type(net4) = <class 'ipaddress.IPv4Network'>
#net4 = 1.1.1.0/31
#net4[0] = 1.1.1.0
#net4[1] = 1.1.1.1
#iface.ip = 1.1.1.1
#str(next_hop) = 1.1.1.0