How do I validate the format of a MAC address?

前端 未结 11 1464
逝去的感伤
逝去的感伤 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 06:51

    I hate programs that force the user to think a like a computer.

    Make it more friendly by accepting any valid format.

    Strip the separator, whatever it is, then get the hex value that's left. That way if a user enters dashes or spaces it also works.

    import string
    allchars = "".join(chr(a) for a in range(256))
    delchars = set(allchars) - set(string.hexdigits)
    
    def checkMAC(s):
      mac = s.translate("".join(allchars),"".join(delchars))
      if len(mac) != 12:
          raise ValueError, "Ethernet MACs are always 12 hex characters, you entered %s" % mac 
      return mac.upper()
    
    
    checkMAC("AA:BB:CC:DD:EE:FF")
    checkMAC("00-11-22-33-44-66")
    checkMAC("1 2 3 4 5 6 7 8 9 a b c")
    checkMAC("This is not a mac")
    

提交回复
热议问题