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

功能描述:检测输入的字符串是否符合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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值