Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?
Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
The accepted answer doesn't work ... which is making me angry. Mask is backwards and doesn't work with any bits that are not a simple 8 bit block (eg /24). I adapted the answer, and it works nicely.
here is a function that returns a dotted binary string to help visualize the masking.. kind of like
ipcalc
output.eg:
from netaddr import all_matching_cidrs
Here is the usage for this method:
Basically you provide an ip address as the first argument and a list of cidrs as the second argument. A list of hits are returned.
From various sources above, and from my own research, this is how I got subnet and address calculation working. These pieces are enough to solve the question and other related questions.
Thank you for your script!
I have work quite a long on it to make everything working... So I'm sharing it here
makeMask function is not working! Only working for /8,/16,/24
Ex:
So I have used another function calcDottedNetmask(mask) from http://code.activestate.com/recipes/576483-convert-subnetmask-from-cidr-notation-to-dotdecima/
Ex:
Ex: for the time being, the function is wrong
So my new addressInNetwork function looks-like:
And now, answer is right!!
I hope that it will help other people, saving time for them!
I don't know of anything in the standard library, but PySubnetTree is a Python library that will do subnet matching.