Skip to content

Instantly share code, notes, and snippets.

@mawillcockson
Created December 28, 2020 11:56
Show Gist options
  • Select an option

  • Save mawillcockson/0676bec3012dce8faa396c5667ed3ffd to your computer and use it in GitHub Desktop.

Select an option

Save mawillcockson/0676bec3012dce8faa396c5667ed3ffd to your computer and use it in GitHub Desktop.
transforms a dotted quad IPv4 address into a single, unsigned 32-bit integer
#!/bin/env python
"""
https://twitter.com/dave_universetf/status/1342688553264762880
"""
import sys
from typing import List
def split_by_dots(dotted_quad: str) -> List[int]:
"turns '1.2.3.4' into [1,2,3,4]"
assert isinstance(dotted_quad, str)
parts = dotted_quad.split(".")
assert len(parts) == 4, "dotted quads are 4 sets of numbers separated by ."
ints = list(map(int, parts))
assert all(0 <= n < 256 for n in ints), "must be from 0 to 255 inclusive"
return ints
def quad_to_int(ints: List[int]) -> int:
"turns [1,2,3,4] into 16909060"
assert isinstance(ints, list)
assert ints, "must have numbers"
assert all(isinstance(n, int) for n in ints), "must all be ints"
byte_values = list()
for num in ints:
byte_values.append(num.to_bytes(1, "big", signed=False))
return int.from_bytes(b"".join(byte_values), "big", signed=False)
if __name__ == "__main__":
assert len(sys.argv) == 2, "only argument should be the dotted quad IPv4 address"
quads = split_by_dots(sys.argv[1])
print(quad_to_int(ints=quads))
@mawillcockson
Copy link
Author

If you desperately want a one-liner:

as_int = lambda s: int.from_bytes(b"".join(n.to_bytes(1, "big", signed=False) for n in map(int, s.split("."))), "big", signed=False)

Then:

>>> as_int("1.2.3.4")
16909060

@mawillcockson
Copy link
Author

From any recent version of Python:

python -c "from urllib.request import urlopen as o;h=o('https://gist.githubusercontent.com/mawillcockson/0676bec3012dce8faa396c5667ed3ffd/raw/ccfca3a9c015eb622517edf6b87c41d83317f68d/as_int.py');exec(h.read().decode());h.close()" "127.0.0.1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment