vinegar.utils.socket

Utilities for dealing with sockets and IP addresses.

vinegar.utils.socket.Inet4SocketAddress

Alias for the address type used with AF_INET sockets.

alias of Tuple[str, int]

vinegar.utils.socket.Inet6SocketAddress

Alias for the address type used with AF_INET6 sockets.

alias of Tuple[str, int, int, int]

vinegar.utils.socket.InetSocketAddress

Alias for the union of Inet4SocketAddress and Inet6SocketAddress.

alias of Union[Tuple[str, int], Tuple[str, int, int, int]]

vinegar.utils.socket.contains_ip_address(ip_address_set: Collection[str], ip_address: str, allow_netmask: bool = True, raise_error_if_malformed: bool = False) bool

Check whether an IP address is contained in a set of IP addresses.

This works with both IPv4 and IPv6 addresses. Optionally, the set of IP addresses may contain address ranges in CIDR notation (e.g. 192.168.0.0/24).

This function supports IPv4-mapped IPv6 addresses. Such addresses are treated like the IPv4 address that they represent.

Parameters:
  • ip_address_set – list or set of IP addresses with which the ip_address shall be compared. If allow_netmask is True, this may include ranges of IP addresses specified using the CIDR notation.

  • ip_address – IP address that shall be tested. This can be an IPv4 or an IPv6 address.

  • allow_netmaskTrue if ip_address_set may contain address ranges, False if it may only contain single IP addresses. The default is True.

  • raise_error_if_malformedTrue if a malformed IP address in ip_address_set` or ``ip_address should result in a ValueError being raised. False if it should result in the entry being ignored (for ip_address_set) or False being returned (for ip_address).

Returns:

True if ip_address is contained in ip_address_set, False otherwise.

vinegar.utils.socket.ipv6_address_unwrap(ipv6_address: str) str

Unwrap an IPv4 address that is encoded in an IPv6 address.

This function works on IPv6 address in the form ::ffff:127.0.0.1 (127.0.0.1 might be any IPv4 address). This so-called IPv4-mapped IPv6 addresses are described in RF 4291. If such an address is encountered (regardless of whether it uses the classic decimal-dot notation or the hexadecimal-colon notation), the actual IPv4 address is extracted and returned.

For any string not representing such an address, this function simply returns the original string.

Parameters:

ipv6_address – string that might represent an IPv4 address wrapped in an IPv6 address (like ::ffff::127.0.0.1).

Returns:

the unwrapped IPv4 address or ipv6_address if the string does not match the expected format.

vinegar.utils.socket.socket_address_to_str(socket_address: Tuple[str, int] | Tuple[str, int, int, int]) str

Return the string representation of a socket address.

Parameters:

socket_address – tuple representing a socket address.