Nov-10-2022, 11:59 PM
while reviewing an old function/module i coded a few years ago, i realized that variable socket.AF_INET6 would not be defined for a platform that was IPv4-only. i am concerned with how the CPython compiler would handle this on such a platform. this code tests socket.has_ipv6 to decide if AF_INET6 is to be imported from socket.
since i have no such platform (everything i have supports IPv6), i tried to test this in a different way. i added a variable that is undefined but i don't know if this test works properly. running this code in python3.8.10 produces no error messages with or without (0 belongs there for intended results) that variable name (see 2nd to last line)
since i have no such platform (everything i have supports IPv6), i tried to test this in a different way. i added a variable that is undefined but i don't know if this test works properly. running this code in python3.8.10 produces no error messages with or without (0 belongs there for intended results) that variable name (see 2nd to last line)
from socket import AF_INET,inet_pton,has_ipv6 if has_ipv6: from socket import AF_INET6 def validip(addr): """Return values indicating if the given IP address is valid for IPv4 and/or IPv6. function validip purpose return 4 if the given IP address is valid for IPv4 or return 6 if the given IP address is valid for IPv6 or return 0 if the given IP address is not valid for either IPv4 or IPv6. return 10 if the given IP address is somehow ambiguous. argument 1 (str,bytes,bytearray) that may be an IP address returns 4 or 6 for the address family if it is valid 0 if the address is not valid IPv4 nor valid IPv6 10 if the address is somehow valid for both IPv4 and IPv6 """ return validipv4(addr)+validipv6(addr) def validipv4(addr): """Return 4 (true) if the given IP address is valid for IPv4 or 0 (false) if not. function validipv4 argument 1 (str,bytes,bytearray) that may be an IPv4 address purpose return 4 if the given IP address is valid for IPv4 or 0 if not returns 4 if the given IP address is valid for IPv4 or 0 if not """ if isinstance(addr,(bytes,bytearray)): addr = ''.join(chr(x)for x in addr) elif not isinstance(addr,str): r = 0 elif '.' not in addr: r = 0 else: try: inet_pton(AF_INET,addr) r = 4 except (OSError,IOError): r = 0 return r def validipv6(addr): """Return 6 (true) if the given IP address is valid for IPv6 or 0 (false) if not. function validipv6 argument 1 (str,bytes,bytearray) that may be an IPv6 address purpose return 6 if the given IP address is valid for IPv6 or 0 if not returns 6 if the given IP address is valid for IPv6 or 0 if not note 0 is also returned if IPv6 is not supported on this platform """ if isinstance(addr,(bytes,bytearray)): addr = ''.join(chr(x)for x in addr) elif not isinstance(addr,str): r = 0 elif ':' not in addr: r = 0 elif not has_ipv6: r = 0 else: try: inet_pton(AF_INET6,addr) r = 6 except (OSError,IOError): r = undefined_variable return r