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
4

2 回答 2

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
于 2013-08-29T17:27:48.293 回答
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")
于 2022-01-24T08:46:52.537 回答