How to compare two IP Addresses and find out if they match fully or partially or they do not match at all

Viewed 5442

I need to compare two Different IP subnet and show result if it is full match, partial match or no match.

I need to use Python.

Can break IP into list but it becomes tricky when there is a subnet involved. For example:

I need to compare a and b where a = 10.10.1.2/25 and b = 10.10.1.6/24 and show the result. I am new to python and not sure how to achieve this task.

3 Answers

You can use ipaddress module of python (in-built)

from  ipaddress import ip_interface
# since you have provided interface address
ip1 = ip_interface.ip_address('10.10.1.2/24')
ip2 = ip_interface.ip_address('10.10.1.6/24')
print(ip1 == ip2)
# answer would be False

Use Python 3 ipaddress library. I guess you need to check if networks of a and b IP addresses overlap.

If we construct Interface Objects, each one will have it's own network attribute accessible through .network.

from ipaddress import ip_interface
a = ip_interface('10.10.1.2/25')
b = ip_interface('10.10.1.6/24')

print(b.network.overlaps(a.network))

Output:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
> True

in the spirit of helping you figure out things instead of providing the solution, try using

  • str.split() (see description here) to break down the IP-addresses into substrings,
  • then == statements to compare them and
  • if, elif to proceed further.

I hope this helps you. :)

Related