-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwk8_ex1.py
92 lines (82 loc) · 2.92 KB
/
wk8_ex1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# IP address validator with Try-Exception as Function
def IPvalidator(ip_address):
ipList = ip_address.split('.')
validIP = True
# Does input have four sections?
if len(ipList) != 4:
#print("Invalid input. Incorrect number of octets. Err 1")
validIP = False
# Are the four sections integers?
# print list(enumerate(ipList))
# octets = []
for i, octet in enumerate(ipList):
try:
ipList[i] = int(octet)
#print(ipList[i])
except TypeError:
#print("Invalid input. %d is not an integer. Err 2" % ipList[i])
validIP = False
except ValueError:
#print("Invalid input. %s is not an integer. Err 2" % octet)
validIP = False
# First octet must be 223 or less
try:
if int(ipList[0]) <= 0 or int(ipList[0]) > 223:
#print("Invalid input. %d is not a valid octet. Err 3" % ipList[0])
validIP = False
except ValueError:
#print("Invalid input. %s is not a valid octet. Err 3" % ipList[0])
validIP = False
# First octet cannot be 127
try:
if int(ipList[0]) == 127:
#print("Invalid input. IP address can not be in 127.0.0.0 subnet. Err 4")
validIP = False
except ValueError:
#print("Invalid input. %s is not an integer. Err 4" % ipList[0])
validIP = False
# IP cannot be on the 169.254.0.0 network
try:
if int(ipList[0]) == 169 and int(ipList[1]) == 254:
#print("Invalid input. IP address can not be in 169.254.0.0 subnet. Err 5")
validIP = False
except ValueError:
#print("Invalid input. %s is not an integer. Err 5" % ipList[1])
validIP = False
# Are the octets integers between 0 and 255?
for i in ipList:
try:
#if int(i) >= 1:
if int(i) < 0 or int(i) > 255:
#print("Invalid input. %d is not a valid octet. Err 6" % int(i))
validIP = False
except ValueError:
validIP = False
return validIP
# Separate executable code from importable code
if __name__ == '__main__':
print
# Create a bunch of test cases
test_ip_addresses = {
'192.168.1' : False,
'10.1.1.' : False,
'10.1.1.x' : False,
'0.77.22.19' : False,
'-1.88.99.17' : False,
'241.17.17.9' : False,
'127.0.0.1' : False,
'169.254.1.9' : False,
'192.256.7.7' : False,
'192.168.-1.7' : False,
'10.1.1.256' : False,
'1.1.1.1' : True,
'223.255.255.255': True,
'223.0.0.0' : True,
'10.200.255.1' : True,
'192.168.17.1' : True,
}
for ip_addr,expected_result in test_ip_addresses.items():
if IPvalidator(ip_addr):
print("%s is valid." % ip_addr)
else:
print("%s is NOT valid." % ip_addr)