Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

python - Check if two CIDR addresses intersect?

Given two CIDR addresses say 192.168.2.0/14 and 192.168.2.0/32

How do I check if two ip addresses overlap in "python2.6"??

I have gone through netaddr and it allows to check if 192.168.2.0 is in CIDR address 192.168.2.0/14 by

from netaddr import IPNetwork, IPAddress
bool = IPAddress("192.168.2.0") in IPNetwork("192.168.2.0/14"):

But how to check for two CIDR address??

I found a reference :: How can I check if an ip is in a network in python

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using ipaddr:

>>> import ipaddr
>>> n1 = ipaddr.IPNetwork('192.168.1.0/24')
>>> n2 = ipaddr.IPNetwork('192.168.2.0/24')
>>> n3 = ipaddr.IPNetwork('192.168.2.0/25')
>>> n1.overlaps(n2)
False
>>> n1.overlaps(n3)
False
>>> n2.overlaps(n3)
True
>>> n2.overlaps(n1)
False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...