is_valid_ip calls `socket.getaddrinfo` with `socket.AI_NUMERICHOST` on
the potential "ip"; even though IP addresses are not hostnames and do
not use the `idna` encoding, `socket.getaddrinfo` will raise
UnicodeError if the potential "ip" is longer than 63 characters long,
the RFC-mandated max hostname length.
Catch these UnicodeErrors and return false for too-long IPs, rather
than raising an exception.
if e.args[0] == socket.EAI_NONAME:
return False
raise
+ except UnicodeError:
+ # `socket.getaddrinfo` will raise a UnicodeError from the
+ # `idna` decoder if the input is longer than 63 characters,
+ # even for socket.AI_NUMERICHOST. See
+ # https://bugs.python.org/issue32958 for discussion
+ return False
return True
self.assertTrue(not is_valid_ip(" "))
self.assertTrue(not is_valid_ip("\n"))
self.assertTrue(not is_valid_ip("\x00"))
+ self.assertTrue(not is_valid_ip("a" * 100))
class TestPortAllocation(unittest.TestCase):