How do I validate the format of a MAC address?

前端 未结 11 1467
逝去的感伤
逝去的感伤 2020-12-15 05:59

What\'s the best way to validate that an MAC address entered by the user?

The format is HH:HH:HH:HH:HH:HH, where each H is a hexadecimal ch

11条回答
  •  天涯浪人
    2020-12-15 07:03

    Dash-separated MAC addresses can also contain a '01-' prefix, which specifies it is an Ethernet MAC address (not token ring, for example ... who uses token ring?).

    Here's something that is somewhat complete and easy to read in a logical step-through way:

    def IsMac(S):
      digits = S.split(':')
      if len(digits) == 1:
        digits = S.split('-')
        if len(digits) == 7:
          if digits[0] != '01':
            return False
          digits.pop(0)
      if len(digits) != 6:
        return False
      for digit in digits:
        if len(digit) != 2:
          return False
        try:
          int(digit, 16)
        except ValueError:
          return False
      return True
    
    
    for test in ('01-07-09-07-b4-ff-a7',  # True
                    '07:09:07:b4:ff:a7',  # True
                    '07-09-07-b4-GG-a7',  # False
                     '7-9-7-b4-F-a7',     # False
                     '7-9-7-b4-0xF-a7'):  # False
      print test, IsMac(test)
    

提交回复
热议问题