File: ipaddress.py

package info (click to toggle)
python-snitun 0.45.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 640 kB
  • sloc: python: 6,681; sh: 5; makefile: 3
file content (26 lines) | stat: -rw-r--r-- 715 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""Utils for handling IP address."""

from functools import lru_cache
import ipaddress
import socket

EMPTY_IP_ADDRESS = ipaddress.IPv4Address(0)
EMPTY_IP_ADDRESS_BYTES = bytes(4)


@lru_cache
def bytes_to_ip_address(data: bytes) -> ipaddress.IPv4Address:
    """Convert bytes into a IP address."""
    try:
        return ipaddress.IPv4Address(socket.inet_ntop(socket.AF_INET, data))
    except (ValueError, OSError):
        return EMPTY_IP_ADDRESS


@lru_cache
def ip_address_to_bytes(ip_address: ipaddress.IPv4Address) -> bytes:
    """Convert a IP address object into bytes."""
    try:
        return socket.inet_pton(socket.AF_INET, str(ip_address))
    except OSError:
        return EMPTY_IP_ADDRESS_BYTES