Skip to content

Instantly share code, notes, and snippets.

@ChrisTM
Last active April 20, 2022 09:35
Show Gist options
  • Select an option

  • Save ChrisTM/7cf6d5409e8cec1497ff to your computer and use it in GitHub Desktop.

Select an option

Save ChrisTM/7cf6d5409e8cec1497ff to your computer and use it in GitHub Desktop.
Convert IPv4 addresses to and from integers
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