Verify IP string is greater or less than another IP string in python
Question:
In a sample code I am taking start IP and end IP as input . Out of which I will create a list of IP pool. I want to add a validation that start IP should be always lesser than end IP.
start_ip = '100.71.9.98'
end_ip = '100.71.9.100'
start_ip < end_ip
False
How can I validate that start_ip should be lesser than end_ip ?
Answers:
Convert the strings to a list of ints.
>>> start_ip = '100.71.9.98'
>>> end_ip = '100.71.9.100'
>>> map(int, start_ip.split('.')) # list(map(int, ...)) in Python 3.x
[100, 71, 9, 98]
>>> map(int, end_ip.split('.'))
[100, 71, 9, 100]
Then, it’s possible to compare them as you want:
>>> '100.71.9.98' < '100.71.9.100'
False
>>> [100, 71, 9, 98] < [100, 71, 9, 100]
True
>>> map(int, start_ip.split('.')) < map(int, end_ip.split('.'))
True
If you use Python 3.x then you can use the ipaddress
stdlib package which has objects designed for ip addresses. These objects support comparison in this way.
import ipaddress
start = ipaddress.IPv4Address('100.71.9.98')
end = ipaddress.IPv4Address('100.71.9.100')
print(start < end)
# True
py2-ipaddress can be used (with some reduced functionality) if you are using Python 2.7.
Standard ipaddress libray (IPv4/IPv6 manipulation library) works like charm:
import ipaddress
if ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2'):
...
In a sample code I am taking start IP and end IP as input . Out of which I will create a list of IP pool. I want to add a validation that start IP should be always lesser than end IP.
start_ip = '100.71.9.98'
end_ip = '100.71.9.100'
start_ip < end_ip
False
How can I validate that start_ip should be lesser than end_ip ?
Convert the strings to a list of ints.
>>> start_ip = '100.71.9.98'
>>> end_ip = '100.71.9.100'
>>> map(int, start_ip.split('.')) # list(map(int, ...)) in Python 3.x
[100, 71, 9, 98]
>>> map(int, end_ip.split('.'))
[100, 71, 9, 100]
Then, it’s possible to compare them as you want:
>>> '100.71.9.98' < '100.71.9.100'
False
>>> [100, 71, 9, 98] < [100, 71, 9, 100]
True
>>> map(int, start_ip.split('.')) < map(int, end_ip.split('.'))
True
If you use Python 3.x then you can use the ipaddress
stdlib package which has objects designed for ip addresses. These objects support comparison in this way.
import ipaddress
start = ipaddress.IPv4Address('100.71.9.98')
end = ipaddress.IPv4Address('100.71.9.100')
print(start < end)
# True
py2-ipaddress can be used (with some reduced functionality) if you are using Python 2.7.
Standard ipaddress libray (IPv4/IPv6 manipulation library) works like charm:
import ipaddress
if ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2'):
...