|
| 1 | +def validateIP(ip): |
| 2 | + ipv4 = ip.split(".") |
| 3 | + ipv6 = ip.split(":") |
| 4 | + if len(ipv4) == 4 and validateIPv4(ipv4): |
| 5 | + return "IPv4" |
| 6 | + elif len(ipv6) == 8 and validateIPv6(ipv6): |
| 7 | + return "IPv6" |
| 8 | + else: |
| 9 | + return "Neither" |
| 10 | + |
| 11 | +def validateIPv4(segments): |
| 12 | + digits = set("1234567890") |
| 13 | + for s in segments: |
| 14 | + # segment too long or too short |
| 15 | + if len(s) > 3 or len(s) == 0: |
| 16 | + return False |
| 17 | + |
| 18 | + # segment has leading 0 |
| 19 | + if len(s) > 1 and s[0] == "0": |
| 20 | + return False |
| 21 | + |
| 22 | + # segment contains non-numeric digits |
| 23 | + if not set(s) < digits: |
| 24 | + return False |
| 25 | + |
| 26 | + # segment is not an int between 0 and 255 inclusive |
| 27 | + if int(s) > 255 or int(s) < 0: |
| 28 | + return False |
| 29 | + return True |
| 30 | + |
| 31 | +def validateIPv6(segments): |
| 32 | + hexDigits = set("1234567890abcdefABCDEF") |
| 33 | + for s in segments: |
| 34 | + # segment too long or too short |
| 35 | + if len(s) > 4 or len(s) == 0: |
| 36 | + return False |
| 37 | + |
| 38 | + # segment contains non-hexadecimal digits |
| 39 | + if not set(s) < hexDigits: |
| 40 | + return False |
| 41 | + return True |
| 42 | + |
| 43 | +def testValidateIPv4(): |
| 44 | + assert validateIPv4(["172", "16", "254", "1"]) |
| 45 | + assert not validateIPv4(["172", "16", "254", "01"]) |
| 46 | + assert not validateIPv4(["172", "16", "256", "1"]) |
| 47 | + assert not validateIPv4(["1e1", "4", "5", "6"]) |
| 48 | + assert not validateIPv4(["1e1", "", "5", "6"]) |
| 49 | + |
| 50 | +def testValidateIPv6(): |
| 51 | + assert validateIPv6(["2001", "0db8", "85a3", "0000", "0000", "8a2e", "0370", "7334"]) |
| 52 | + assert validateIPv6(["2001", "db8", "85a3", "0", "0", "8A2E", "0370", "7334"]) |
| 53 | + assert not validateIPv6(["2001", "0db8", "85a3", "", "", "8A2E", "0370", "7334"]) |
| 54 | + assert not validateIPv6(["02001", "0db8", "85a3", "0000", "0000", "8a2e", "0370", "7334"]) |
| 55 | + assert not validateIPv6(["GGGG", "0db8", "85a3", "0000", "0000", "8a2e", "0370", "7334"]) |
| 56 | + |
| 57 | +def testValidateIP(): |
| 58 | + assert validateIP("172.16.254.1") == "IPv4" |
| 59 | + assert validateIP("172.16.254.01") == "Neither" |
| 60 | + assert validateIP("172.16.254.01") == "Neither" |
| 61 | + assert validateIP("172.16.256.1") == "Neither" |
| 62 | + |
| 63 | + assert validateIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334") == "IPv6" |
| 64 | + assert validateIP("2001:db8:85a3:0:0:8A2E:0370:7334") == "IPv6" |
| 65 | + assert validateIP("2001:0db8:85a3:::8A2E:0370:7334") == "Neither" |
| 66 | + assert validateIP("02001:db8:85a3:0:0:8A2E:0370:7334") == "Neither" |
| 67 | + |
| 68 | +def main(): |
| 69 | + testValidateIPv4() |
| 70 | + testValidateIPv6() |
| 71 | + testValidateIP() |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + main() |
0 commit comments