一、自动动手,丰衣足食
#encoding=utf-8 import os,sys def check_ip(ipaddr): addr = ipaddr.strip().split('.') #切割IP地址为一个列表 #print addr if len(addr) != 4: #切割后列表必须有4个参数 print "check ip address failed1!" sys.exit() for i in range(4): try: addr[i]=int(addr[i]) #每个参数必须为数字,否则校验失败 except: print "check ip address failed!" sys.exit() if addr[i]<=255 and addr[i]>=0: #每个参数值必须在0-255之间 pass else: print "check ip address failed!" sys.exit() print "check ip address success!" if __name__ == '__main__': ip = raw_input("please input check ip:") # ip = "172.29.41.57" check_ip(ip)
二、使用python库
import socket def valid_ip(address): try: socket.inet_aton(address) return True except: return False
此方法存在局限性,可以检测IP地址每个字段的合法性,无法检查字段个数。
print valid_ip('10.10.20.30')
-> True
print valid_ip('999.10.20.30')
-> False
print valid_ip('gibberish')
-> False
print valid_ip('172.29.41')
-> True