Python IP地址合法性的校驗
阿新 • • 發佈:2019-01-30
#!/usr/bin/python
import os,sys
def check_ip(ipaddr):
addr=ipaddr.strip().split('.') #切割IP地址為一個列表
print "check ip address failed!"
sys.exit(1)
for i in range(4):
try:
addr[i]=int(addr[i]) #每個引數必須為數字,否則校驗失敗
except:
print "check ip address failed!"
sys.exit(1)
if addr[i]<=255 and addr[i]>=0: #每個引數值必須在0-255之間
pass
else:
print "check ip address failed!"
sys.exit()
i+=1
else:
print "check ip address success!"
if len(sys.argv)!=2: #傳參加本身長度必須為2
print "Example: %s 10.0.0.1 "%sys.argv[0]
sys.exit()
else:
check_ip(sys.argv[1]) #滿足條件呼叫校驗IP函式
import os,sys
def check_ip(ipaddr):
addr=ipaddr.strip().split('.') #切割IP地址為一個列表
#print addr
if len(addr) != 4: #切割後列表必須有4個引數print "check ip address failed!"
sys.exit(1)
for i in range(4):
try:
addr[i]=int(addr[i]) #每個引數必須為數字,否則校驗失敗
except:
print "check ip address failed!"
sys.exit(1)
if addr[i]<=255 and addr[i]>=0: #每個引數值必須在0-255之間
pass
else:
print "check ip address failed!"
sys.exit()
i+=1
else:
print "check ip address success!"
if len(sys.argv)!=2: #傳參加本身長度必須為2
print "Example: %s 10.0.0.1 "%sys.argv[0]
sys.exit()
else:
check_ip(sys.argv[1]) #滿足條件呼叫校驗IP函式