Last active
May 12, 2019 15:29
-
-
Save D4R4/c33867782878ae050e4e3bfce872cc13 to your computer and use it in GitHub Desktop.
Python functions to mess around with IP Addresses and ranges, useful to prase data from directories like RIPE or etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment