4 ms·
Ehm, how do you check whether an IP address is inside of a specific network with strings? Or how two networks overlap? How many addresses a network has? Hint:
by hynek 14y ago
Ehm, how do you check whether an IP address is inside of a specific network with strings? Or how two networks overlap? How many addresses a network has?
Hint: there’s more than /24 networks and IPv6 makes it even more complicated.
- sho_hn 14y agoWhile I don't share the OP's worry, I'm guessing he was thinking of utility functions operating on strings as the alternative.
- hynek 14y agoYou can’t hide the complexity of doing that right but OTOH the ipaddress objects have useful str() methods: >>> str(ipaddress.ip_address('127.0.0.1')) '127.0.0.1' >>> str(ipaddress.ip_address('::1')) '::1' >>> str(ipaddress.ip_network('192.168.42.0/24')) '192.168.42.0/24' But you can do stuff like: >>> ipaddress.ip_address('192.168.42.23') in ipaddress.ip_network('192.168.42.0/24') True >>> ipaddress.ip_address('192.168.41.23') in ipaddress.ip_network('192.168.42.0/24') False or for addr in ipaddress.ip_network('192.168.42.0/24'): print(adds) Etc. I strongly suggest to have a look at http://docs.python.org/dev/howto/ipaddress.html#ipaddress-howto http://docs.python.org/dev/howto/ipaddress.html#ipaddress-ho... to have an overview over it’s functionality – unfortunately the API docs aren’t done yet, but will be for 3.3 final. edit fixed code markup
- sho_hn 14y agoJust for the record, I agree that the problem space is such that a utility class is warranted having written code dealing with IP addresses in the past; I was just speculating about the OP's thoughts :).
- est 14y agoyes, just one or two utility functions would do. IMHO there is no need to initialize a class and call a method just for checking network overlap/boundaries.
- baq 14y agono need to use it, really. you can pretend it doesn't exist. problem solved.
- alex-g 14y agoIt's not a high overhead. Your string method would have to do basically the same thing as the ipaddress initialization and method call. As a benefit, with ipaddress you don't have to re-parse the string every time you want to manipulate it as an address; and you get a bit of typechecking and documentation from using a specialized class.