Skip to content

Instantly share code, notes, and snippets.

@hirusha-adi
Last active October 24, 2024 06:25
Show Gist options
  • Save hirusha-adi/8ee951a228e11b8b2af44ebf94e3b317 to your computer and use it in GitHub Desktop.
Save hirusha-adi/8ee951a228e11b8b2af44ebf94e3b317 to your computer and use it in GitHub Desktop.
Python IPV4 / IPV6 Validation (Advanced)
# based on: https://docs.python.org/3/library/ipaddress.html
import ipaddress
import typing
def is_ipcheck(
value: str,
check_type: typing.Literal[
"addr",
"network",
"interface",
"ipv4",
"ipv4netork",
"ipv4interface",
"ipv6",
"ipv6network",
"ipv6interface",
],
) -> bool:
"""
Check if a given string is a valid IP address of a given type.
Args:
value (str): The string to check.
check_type (typing.Literal[...]):
The type of IP address to check for. The following values are valid:
- "addr": Any valid IP address (both IPv4 and IPv6).
- "network": Any valid network address (both IPv4 and IPv6).
- "interface": Any valid interface address (both IPv4 and IPv6).
- "ipv4": A valid IPv4 address.
- "ipv4network": A valid IPv4 network address.
- "ipv4interface": A valid IPv4 interface address.
- "ipv6": A valid IPv6 address.
- "ipv6network": A valid IPv6 network address.
- "ipv6interface": A valid IPv6 interface address.
Returns:
bool:
True if the string is a valid IP address of the given type,
False otherwise.
"""
try:
{
"addr": ipaddress.ip_address, # https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_address
"network": ipaddress.ip_network, # https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network
"interface": ipaddress.ip_interface, # https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_interface
"ipv4": ipaddress.IPv4Address, # https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address
"ipv4network": ipaddress.IPv4Network, # https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network
"ipv4interface": ipaddress.IPv4Interface, # https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Interface
"ipv6": ipaddress.IPv6Address, # https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Address
"ipv6network": ipaddress.IPv6Network, # https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network
"ipv6interface": ipaddress.IPv6Interface, # https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Interface
}[check_type](value)
return True
except (ValueError, KeyError):
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment