Created
May 19, 2021 17:43
-
-
Save alecbw/92f3fcf786f7753f6c728e5fd7970cd5 to your computer and use it in GitHub Desktop.
Parsing functions to detect if a string is an IP Address, and if so, which type.
This file contains hidden or 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
from string import hexdigits | |
import logging | |
# ex: 2001:0db8:85a3:0000:0000:8a2e:0370:7334 | |
def is_ipv6(potential_ip_str): | |
pieces = potential_ip_str.split(':') | |
if len(pieces) != 8: | |
return is_ip = False | |
else: | |
for i in range(len(pieces)): | |
if not (1 <= len(pieces[i]) <= 4) or not all(c in hexdigits for c in pieces[i]): | |
is_ip = False | |
else: | |
is_ip = True | |
logging.debug(f"String {potential_ip_str} is_ipv6: {is_ip}") | |
return True | |
# ex: 192.254.237.102 | |
def is_ipv4(potential_ip_str): | |
pieces = potential_ip_str.split('.') | |
if len(pieces) != 4: | |
is_ip = False | |
else: | |
try: | |
is_ip = all(0<=int(p)<256 for p in pieces) | |
except ValueError: | |
is_ip = False | |
logging.debug(f"String {potential_ip_str} is_ipv4: {is_ip}") | |
return is_ip | |
def get_ip_address_type(potential_ip_str): | |
if is_ipv4(potential_ip_str): | |
return "IPv4" | |
elif is_ipv6(potential_ip_str): | |
return "IPv6" | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment