Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
Given an IP address (say 192.168.0.1), how would I check if it's in an organization (say 192.168.0.0/24) in Python?

Are there general instruments in Python for IP address control? Stuff like host queries, IP address to int, network address with netmask to int, etc? Ideally in the standard Python library for 2.5.

1 Answer

0 votes
by (26.4k points)

You can do it with the socket and struct modules without an excess of additional exertion. I added a little to the article as follows: 

import socket,struct

def makeMask(n):

    "return a mask of n bits as a long integer"

    return (2L<<n-1) - 1

def dottedQuadToNum(ip):

    "convert decimal dotted quad string to long integer"

    return struct.unpack('L',socket.inet_aton(ip))[0]

def networkMask(ip,bits):

    "Convert a network address to a long integer" 

    return dottedQuadToNum(ip) & makeMask(bits)

def addressInNetwork(ip,net):

   "Is an address in a network"

   return ip & net == net

address = dottedQuadToNum("192.168.1.1")

networka = networkMask("10.0.0.0",24)

networkb = networkMask("192.168.0.0",24)

print (address,networka,networkb)

print addressInNetwork(address,networka)

print addressInNetwork(address,networkb)

Output:

False

True

On the off chance that you simply need a single function that takes strings it would resemble this:

import socket,struct

def addressInNetwork(ip,net):

   "Is an address in a network"

   ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]

   netaddr,bits = net.split('/')

   netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)

   return ipaddr & netmask == netmask

Looking for a good python tutorial course? Join the python certification course and get certified.

Related questions

+1 vote
1 answer
asked Sep 26, 2019 in AWS by chandra (29.3k points)
0 votes
1 answer
+1 vote
1 answer
0 votes
2 answers

Browse Categories

...