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.
I'm not a fan of using modules when they are not needed. This job only requires simple math, so here is my simple function to do the job:
Then to use it:
That's it, this is much faster than the solutions above with the included modules.
If you do not want to import other modules you could go with:
Here is a class I wrote for longest prefix matching:
And here is a test program:
I tried one subset of proposed solutions in these answers.. with no success, I finally adapted and fixed the proposed code and wrote my fixed function.
I tested it and works at least on little endian architectures--e.g.x86-- if anyone likes to try on a big endian architecture, please give me feedback.
IP2Int
code comes from this post, the other method is a fully (for my test cases) working fix of previous proposals in this question.The code:
Hope useful,
I like to use netaddr for that:
As arno_v pointed out in the comments, new version of netaddr does it like this:
The choosen answer has a bug.
Following is the correct code:
Note:
ipaddr & netmask == netaddr & netmask
instead ofipaddr & netmask == netmask
.I also replace
((2L<<int(bits)-1) - 1)
with((1L << int(bits)) - 1)
, as the latter seems more understandable.