Created
October 24, 2024 05:57
-
-
Save hirusha-adi/5ed5000246e16dfa035ea604362c763f to your computer and use it in GitHub Desktop.
Python IPV4 / IPV6 Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# based on: https://docs.python.org/3/library/ipaddress.html | |
import ipaddress | |
def is_ipaddr(input_str: str) -> bool: | |
""" | |
Checks if input string is a valid IP address (both IPv4 and IPv6). | |
Args: | |
input_str (str): The string to check. | |
Returns: | |
bool: | |
True if the string is a valid IP address, | |
False otherwise. | |
""" | |
try: | |
ipaddress.ip_address(input_str) | |
return True | |
except ValueError: | |
return False | |
def is_ipv4(input_str: str) -> bool: | |
""" | |
Checks if input string is a valid IPv4 address. | |
Args: | |
input_str (str): The string to check. | |
Returns: | |
bool: | |
True if the string is a valid IPv4 address, | |
False otherwise. | |
""" | |
try: | |
ipaddress.IPv4Address(input_str) | |
return True | |
except ValueError: | |
return False | |
def is_ipv6(input_str: str) -> bool: | |
""" | |
Checks if input string is a valid IPv6 address. | |
Args: | |
input_str (str): The string to check. | |
Returns: | |
bool: | |
True if the string is a valid IPv6 address, | |
False otherwise. | |
""" | |
try: | |
ipaddress.IPv6Address(input_str) | |
return True | |
except ValueError: | |
return False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment