|
| 1 | +# https://www.geeksforgeeks.org/convert-ip-address-to-integer-and-vice-versa/ |
| 2 | + |
| 3 | + |
| 4 | +def ipv4_to_decimal(ipv4_address: str) -> int: |
| 5 | + """ |
| 6 | + Convert an IPv4 address to its decimal representation. |
| 7 | +
|
| 8 | + Args: |
| 9 | + ip_address: A string representing an IPv4 address (e.g., "192.168.0.1"). |
| 10 | +
|
| 11 | + Returns: |
| 12 | + int: The decimal representation of the IP address. |
| 13 | +
|
| 14 | + >>> ipv4_to_decimal("192.168.0.1") |
| 15 | + 3232235521 |
| 16 | + >>> ipv4_to_decimal("10.0.0.255") |
| 17 | + 167772415 |
| 18 | + >>> ipv4_to_decimal("10.0.255") |
| 19 | + Traceback (most recent call last): |
| 20 | + ... |
| 21 | + ValueError: Invalid IPv4 address format |
| 22 | + >>> ipv4_to_decimal("10.0.0.256") |
| 23 | + Traceback (most recent call last): |
| 24 | + ... |
| 25 | + ValueError: Invalid IPv4 octet 256 |
| 26 | + """ |
| 27 | + |
| 28 | + octets = [int(octet) for octet in ipv4_address.split(".")] |
| 29 | + if len(octets) != 4: |
| 30 | + raise ValueError("Invalid IPv4 address format") |
| 31 | + |
| 32 | + decimal_ipv4 = 0 |
| 33 | + for octet in octets: |
| 34 | + if not 0 <= octet <= 255: |
| 35 | + raise ValueError(f"Invalid IPv4 octet {octet}") # noqa: EM102 |
| 36 | + decimal_ipv4 = (decimal_ipv4 << 8) + int(octet) |
| 37 | + |
| 38 | + return decimal_ipv4 |
| 39 | + |
| 40 | + |
| 41 | +def alt_ipv4_to_decimal(ipv4_address: str) -> int: |
| 42 | + """ |
| 43 | + >>> alt_ipv4_to_decimal("192.168.0.1") |
| 44 | + 3232235521 |
| 45 | + >>> alt_ipv4_to_decimal("10.0.0.255") |
| 46 | + 167772415 |
| 47 | + """ |
| 48 | + return int("0x" + "".join(f"{int(i):02x}" for i in ipv4_address.split(".")), 16) |
| 49 | + |
| 50 | + |
| 51 | +def decimal_to_ipv4(decimal_ipv4: int) -> str: |
| 52 | + """ |
| 53 | + Convert a decimal representation of an IP address to its IPv4 format. |
| 54 | +
|
| 55 | + Args: |
| 56 | + decimal_ipv4: An integer representing the decimal IP address. |
| 57 | +
|
| 58 | + Returns: |
| 59 | + The IPv4 representation of the decimal IP address. |
| 60 | +
|
| 61 | + >>> decimal_to_ipv4(3232235521) |
| 62 | + '192.168.0.1' |
| 63 | + >>> decimal_to_ipv4(167772415) |
| 64 | + '10.0.0.255' |
| 65 | + >>> decimal_to_ipv4(-1) |
| 66 | + Traceback (most recent call last): |
| 67 | + ... |
| 68 | + ValueError: Invalid decimal IPv4 address |
| 69 | + """ |
| 70 | + |
| 71 | + if not (0 <= decimal_ipv4 <= 4294967295): |
| 72 | + raise ValueError("Invalid decimal IPv4 address") |
| 73 | + |
| 74 | + ip_parts = [] |
| 75 | + for _ in range(4): |
| 76 | + ip_parts.append(str(decimal_ipv4 & 255)) |
| 77 | + decimal_ipv4 >>= 8 |
| 78 | + |
| 79 | + return ".".join(reversed(ip_parts)) |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == "__main__": |
| 83 | + import doctest |
| 84 | + |
| 85 | + doctest.testmod() |
0 commit comments