关闭

Python----检测字符串是否是十进制格式的IP地址

标签: 正则表达式网络ipv4
341人阅读 评论(0) 收藏 举报
分类:

功能描述:检测输入的字符串是否符合IPv4规范的IP

参数:ipStr任意字符串

返回值:True/False

约束:不允许使用正则表达式

IPv4地址范围说明:

A类地址:1.*.*.* 到127.*.*.* 和 0.0.0.0(全网络地址)

B类地址:128.*.*.* 到191.*.*.* 

C类地址:192.*.*.* 到223.*.*.*

D类地址:224.*.*.* 到239.255.255.255 

E类地址:240.0.0.0 到255.255.255.255

*表示0~255

关键点:字符串、IPv4规范


def checkIPv4(ipStr):
  print '+++++++++++++++++++++++++++++++++++++++'
  print 'The Input Ip String is =',ipStr
  IPv4List  = ipStr.split('.')
  print 'Ip String convert to ip List is =',IPv4List
  IPv4Count = len(IPv4List)
  print 'The Num of IPv4List is =',IPv4Count

  if(4!=IPv4Count):
    return False

  for i in range(0,IPv4Count):
    Each_IPv4_List_Len = len(IPv4List[i])
    print IPv4List[i],Each_IPv4_List_Len
    if Each_IPv4_List_Len < 1 or Each_IPv4_List_Len > 3:
      print "Error: The Len of %s is %d" % (IPv4List[i],Each_IPv4_List_Len)
      return False
    
    for j in range(0,Each_IPv4_List_Len):
      if IPv4List[i][j]<'0' or IPv4List[i][j]>'9':
        print "Error: The %s is not only number" % IPv4List[i]
        return False

    value_of_each_IPv4_List = int(IPv4List[i])
    if(value_of_each_IPv4_List<0 or value_of_each_IPv4_List>255):
      print "The Number of %s is overflow" % IPv4List[i]
      return False

  if int(IPv4List[0]) == 0:
    if int(IPv4List[1])==0 and int(IPv4List[2])==0 and int(IPv4List[3])==0 :
      pass
    else:
      print "Error: Not all is Zero"
      return False

  return True
    
print checkIPv4("192.168.1.1")
print checkIPv4("0.0.0.0")
print checkIPv4("255.255.255.255")
print checkIPv4("1.2.3.a")
print checkIPv4("1231.231.3.4")
print checkIPv4("0.1.1.1")
print checkIPv4("-1.2.3.4")
print checkIPv4("*&^.3.%.3")



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12412次
    • 积分:1590
    • 等级:
    • 排名:千里之外
    • 原创:149篇
    • 转载:8篇
    • 译文:3篇
    • 评论:0条