You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importreimportunittestdefis_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) orre.match(ipv6, input_str)) isnotNoneclassTestIsIPAddr(unittest.TestCase):
deftest_ipv6(self):
self.assertTrue(is_ipaddr('::1'))
self.assertTrue(is_ipaddr('2001:0db8:85a3:0000:0000:8a2e:0370:7334'))
self.assertTrue(is_ipaddr('::'))
self.assertFalse(is_ipaddr(':'))
self.assertFalse(is_ipaddr('::1:'))
if__name__=='__main__':
unittest.main()
Result:
.F
======================================================================
FAIL: test_ipv6 (__main__.TestIsIPAddr.test_ipv6)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/B84CC2894CC241BC/development/hirusha-adi/Near/tmp.py", line 41, in test_ipv6
self.assertFalse(is_ipaddr('::1:'))
AssertionError: True is not false
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (failures=1)
Consider using socket or ipaddress modules in python
The text was updated successfully, but these errors were encountered:
Result:
Consider using
socket
oripaddress
modules in pythonThe text was updated successfully, but these errors were encountered: