Python :: Aufgabe #57
2 Lösungen

IPv6 Adresse überprüfen
Anfänger - Python
von pocki
- 26.11.2014 um 12:03 Uhr
Schreibe eine Funktion, welche eine Zeichenfolge entgegen nimmt und diese auf eine gültige IPv6 Adresse prüft.
Ohne Verwendung der internen vorhandenen Überprüfungsfunktionen!
IPv6 Adressnotation Wikipedia
Ohne Verwendung der internen vorhandenen Überprüfungsfunktionen!
IPv6 Adressnotation Wikipedia
Lösungen:
Eine Lösung für vollständig ausgeschriebene IPv6 Adressen und gefilterten Kurzschreibweisen.
Python-Code

#!/usr/bin/env python3 def ipv6Check(): """ check if input is a valid ipv6 """ stdAdd = ["::1"] # add futher ddresses if needed ipv6Value = input("Please enter address: ") ipv6Len = len(ipv6Value) if ipv6Len >= 3 and ipv6Len <= 39: #check further if ipv6Value in stdAdd: print("Address is valid. ") else: # chek max 4 chars to get ":" checkPosStart = 0 while checkPosStart <= ipv6Len: try: if ipv6Value[checkPosStart+4] == ":": for i in range(0,4): if checkChars(ipv6Value[checkPosStart+i]) == False: print("A unvalid char detected. IPv6 fail.",ipv6Value[checkPosStart+i]) exit() except IndexError: pass checkPosStart += 4 else: print("Not a valid ipv6 address") def checkChars(char): validChars = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] if char in validChars: return True else: return False def main(): ipv6Check() if __name__ == "__main__": main()
Eine verbesserte Lösung, die auch Kurzschreibweise zulässt. =)
Python-Code

#!/usr/bin/env python3 # # - ipv6Check is used with string comparison. # - the length of a blog is also check by 4 digits. ################################################### def ipv6Check(): """ check if input is a valid ipv6 """ stdAdd = ["::1"] # add futher ddresses if needed ipv6Value = input("Please enter address: ") ipv6Len = len(ipv6Value) if ipv6Len >= 3 and ipv6Len <= 39: #check further if ipv6Value in stdAdd: print("Address is valid. ") else: # chek max 4 chars to get ":" checkPosStart = 0 while checkPosStart <= ipv6Len: try: counter = 0 while ipv6Value[checkPosStart] != ":": if counter > 3: print("No IPv6 address.") exit() else: if checkChars(ipv6Value[checkPosStart]) == False: print("A unvalid char detected. IPv6 fail.",ipv6Value[checkPosStart]) exit() counter += 1 checkPosStart += 1 counter = 0 except IndexError: pass checkPosStart += 1 print("Address is valid.") else: print("Not a valid ipv6 address") def checkChars(char): """ check if char is a valid hex degit """ validChars = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] if char in validChars: return True else: return False def main(): ipv6Check() if __name__ == "__main__": main()