ungleich-learning-circle/pedro/ipv6-stuff/overlap.py

54 lines
1.6 KiB
Python

import ipaddress
import argparse
# for exit codes
import sys
def proc_args():
# src https://docs.python.org/3/library/argparse.html#description
parser = argparse.ArgumentParser(description='Compare two IPs and check if they are overlapped or not')
parser.add_argument('ip1', type=str,
help='IPv6 number 1')
parser.add_argument('ip2', type=str,
help='IPv6 number 2')
args = parser.parse_args()
return args
# - Write a python script that checks whether two IPv6 networks are overlapping
# - *overlap.py ip1 ip2*
def parse_ip(ip_arg):
if('/' in ip_arg):
ip_arg = ip_arg.split('/')[0]
else:
# if no network specified, assume a netmask of /48 for all of them
ip_arg = ip_arg + '/48'
# strict false to avoid -> https://stackoverflow.com/questions/40839147/ipaddress-module-valueerrors-has-host-bits-set-self
# strict is passed to IPv4Network or IPv6Network constructor. A ValueError is
# raised if address does not represent a valid IPv4 or IPv6 address, or if
# the network has host bits set. -> src https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network
return ipaddress.IPv6Network(ip_arg, False)
def main():
is_overlap=False
args = proc_args()
try:
ip1 = parse_ip(args.ip1)
ip2 = parse_ip(args.ip2)
except:
print('incorrect IPv6 address')
# src https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network.overlaps
is_overlap = ip1.overlaps(ip2)
if(is_overlap):
print('overlap')
sys.exit(1)
else:
print('no overlap')
sys.exit(0)
if __name__ == "__main__":
main()