Question

How do I check whether an IP is contained in a network with python?

Eg:

# pseudo code
IP('10.40.0.1').contained_in(CDIR('10.40.0.0/24)) == True
Was it helpful?

Solution

Using Python 3.3+ ipaddress

>>> import ipaddress
>>> ipaddress.ip_address('10.40.0.1') in ipaddress.ip_network('10.40.0.0/24')
True
>>> ipaddress.ip_address('10.40.2.1') in ipaddress.ip_network('10.40.0.0/24')
False

There's also backport of ipaddress.

Using ipaddr

>>> import ipaddr
>>> ipaddr.IPAddress('10.40.0.1') in ipaddr.IPNetwork('10.40.0.0/24')
True
>>> ipaddr.IPAddress('10.40.2.1') in ipaddr.IPNetwork('10.40.0.0/24')
False

OTHER TIPS

  • you can check if ip exist in network using hek
import hek

ip = "192.168.0.1" # targeted ip address

result = hek.ipstuff.checkip(ip) # checking if ip exist, It'll return True is exist and False if not.

if result == True:
    print("ip exist")
elif result == False:
    print("ip doesn't exist")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top