Last active
October 24, 2024 05:54
-
-
Save hirusha-adi/58f576386e2816ecd41fc742ae76aef7 to your computer and use it in GitHub Desktop.
Python IPV4 / IPV6 Regular Expressions (REGEX)
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
import re | |
def is_ipaddr(input_str: str) -> bool: | |
""" | |
Check if input string is a valid IP address (both IPv4 and IPv6). | |
Based on: | |
IPv4: https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp | |
IPv6: https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses | |
Args: | |
input_str (str): The string to check. | |
Returns: | |
bool: | |
True if the string is a valid IP address, | |
False if it is not. | |
""" | |
ipv4 = r'^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$' | |
ipv6 = r'(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))' | |
return (re.match(ipv4, input_str) or re.match(ipv6, input_str)) is not None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment