Created
December 28, 2020 11:56
-
-
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
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
| #!/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)) |
Author
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
If you desperately want a one-liner:
Then: