Last active
April 20, 2022 09:35
-
-
Save ChrisTM/7cf6d5409e8cec1497ff to your computer and use it in GitHub Desktop.
Convert IPv4 addresses to and from integers
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
| def ip_to_int(dotted_address): | |
| """ | |
| Return the integer representation of a dotted IPV4 address. | |
| Useful for comparisons and as a sort key. For example: | |
| sorted(['0.0.0.100','0.0.0.20', '0.0.0.3'], key=ip_to_int) | |
| puts '0.0.0.20' in the middle instead of at the end, which a naive string | |
| sort would do. | |
| """ | |
| octets = map(int, dotted_address.split('.')) | |
| return ( | |
| (octets[0] << 24) + | |
| (octets[1] << 16) + | |
| (octets[2] << 8) + | |
| (octets[3] << 0) | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment