2

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
nemesisdesign
  • 8,159
  • 12
  • 58
  • 97

2 Answers2

4

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • cool, it's possible to do that with netaddr too. Wondering what's the difference between netaddr and ipaddr. Thank you! – nemesisdesign Aug 29 '13 at 17:35
  • @nemesisdesign, You can use `ipaddr.IPNetwork(..) in ipaddr.IPNetwork(..)`. Unfortunately `ipaddress.ip_network(..) in ipaddress.ip_network(..)` does not work. – falsetru Aug 29 '13 at 17:47
  • @nemesisdesign, You can use `ipaddress.ip_interface(u'x.y.z.w/n') in ipaddress.ip_network(u'x.y.z.w/n')`. But I'm not sure it is correct way. – falsetru Aug 29 '13 at 17:57
0
  • 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")