Skip to content

net_utils.py

Net utilities.

__all__ = ['resolve_hostname', 'validate_scheme_host_port'] module-attribute

is_valid_hostname(hostname)

Validate a host name.

Parameters:

Name Type Description Default
hostname str

host name to validate.

required

Returns:

Type Description
bool

True if is valid else False.

Source code in solnlib/net_utils.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def is_valid_hostname(hostname: str) -> bool:
    """Validate a host name.

    Arguments:
        hostname: host name to validate.

    Returns:
        True if is valid else False.
    """
    # Splunk IPv6 support.
    # https://docs.splunk.com/Documentation/Splunk/9.0.0/Admin/ConfigureSplunkforIPv6#Change_the_prioritization_of_IPv4_and_IPv6_communications
    if hostname == "[::1]":
        return True

    if len(hostname) > 255:
        return False
    if hostname[-1:] == ".":
        hostname = hostname[:-1]
    allowed = re.compile(r"(?!-)(::)?[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
    return all(allowed.match(x) for x in hostname.split("."))

is_valid_ip(addr)

Validate an IPV4 address.

Parameters:

Name Type Description Default
addr str

IP address to validate.

required

Returns:

Type Description
bool

True if is valid else False.

Source code in solnlib/net_utils.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def is_valid_ip(addr: str) -> bool:
    """Validate an IPV4 address.

    Arguments:
        addr: IP address to validate.

    Returns:
        True if is valid else False.
    """

    ip_rx = re.compile(
        r"""
        ^(((
              [0-1]\d{2}                  # matches 000-199
            | 2[0-4]\d                    # matches 200-249
            | 25[0-5]                     # matches 250-255
            | \d{1,2}                     # matches 0-9, 00-99
        )\.){3})                          # 3 of the preceding stanzas
        ([0-1]\d{2}|2[0-4]\d|25[0-5]|\d{1,2})$     # final octet
    """,
        re.VERBOSE,
    )

    try:
        return ip_rx.match(addr.strip())
    except AttributeError:
        # Value was not a string
        return False

is_valid_port(port)

Validate a port.

Parameters:

Name Type Description Default
port Union[str, int]

port to validate.

required

Returns:

Type Description
bool

True if is valid else False.

Source code in solnlib/net_utils.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def is_valid_port(port: Union[str, int]) -> bool:
    """Validate a port.

    Arguments:
        port: port to validate.

    Returns:
        True if is valid else False.
    """

    try:
        return 0 < int(port) <= 65535
    except ValueError:
        return False

is_valid_scheme(scheme)

Validate a scheme.

Parameters:

Name Type Description Default
scheme str

scheme to validate.

required

Returns:

Type Description
bool

True if is valid else False.

Source code in solnlib/net_utils.py
126
127
128
129
130
131
132
133
134
135
136
def is_valid_scheme(scheme: str) -> bool:
    """Validate a scheme.

    Arguments:
        scheme: scheme to validate.

    Returns:
        True if is valid else False.
    """

    return scheme.lower() in ("http", "https")

resolve_hostname(addr)

Try to resolve an IP to a host name and returns None on common failures.

Parameters:

Name Type Description Default
addr str

IP address to resolve.

required

Returns:

Type Description
Optional[str]

Host name if success else None.

Raises:

Type Description
ValueError

If addr is not a valid address.

Source code in solnlib/net_utils.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def resolve_hostname(addr: str) -> Optional[str]:
    """Try to resolve an IP to a host name and returns None on common failures.

    Arguments:
        addr: IP address to resolve.

    Returns:
        Host name if success else None.

    Raises:
        ValueError: If `addr` is not a valid address.
    """

    if is_valid_ip(addr):
        try:
            name, _, _ = socket.gethostbyaddr(addr)
            return name
        except socket.gaierror:
            # [Errno 8] nodename nor servname provided, or not known
            pass
        except socket.herror:
            # [Errno 1] Unknown host
            pass
        except socket.timeout:
            # Timeout.
            pass

        return None
    else:
        raise ValueError("Invalid ip address.")

validate_scheme_host_port(scheme, host, port)

Validates scheme, host and port.

Parameters:

Name Type Description Default
scheme str

scheme to validate.

required
host str

hostname to validate.

required
port Union[str, int]

port to validate.

required

Raises:

Type Description
ValueError

if scheme, host or port are invalid.

Source code in solnlib/net_utils.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def validate_scheme_host_port(scheme: str, host: str, port: Union[str, int]):
    """Validates scheme, host and port.

    Arguments:
        scheme: scheme to validate.
        host: hostname to validate.
        port: port to validate.

    Raises:
        ValueError: if scheme, host or port are invalid.
    """
    if scheme is not None and not is_valid_scheme(scheme):
        raise ValueError("Invalid scheme")
    if host is not None and not is_valid_hostname(host):
        raise ValueError("Invalid host")
    if port is not None and not is_valid_port(port):
        raise ValueError("Invalid port")