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.
Marc's code is nearly correct. A complete version of the code is -
Obviously from the same sources as above...
A very Important note is that the first code has a small glitch - The IP address 255.255.255.255 also shows up as a Valid IP for any subnet. I had a heck of time getting this code to work and thanks to Marc for the correct answer.
This code is working for me on Linux x86. I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.
Example:
Not in the Standard library for 2.5, but ipaddr makes this very easy. I believe it is in 3.3 under the name ipaddress.
This article shows you can do it with
socket
andstruct
modules without too much extra effort. I added a little to the article as follows:This outputs:
If you just want a single function that takes strings it would look like this:
Relating to all of the above, I think socket.inet_aton() returns bytes in network order, so the correct way to unpack them is probably
Using ipaddress (in the stdlib since 3.3, at PyPi for 2.6/2.7):
If you want to evaluate a lot of IP addresses this way, you'll probably want to calculate the netmask upfront, like
Then, for each address, calculate the binary representation with one of
Finally, you can simply check: