How do you validate that a string is a valid MAC address in C?

前端 未结 4 592
挽巷
挽巷 2020-12-22 14:43

example:

12:45:ff:ab:aa:cd    is valid
45:jj:jj:kk:ui>cd    is not valid
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-22 15:15

    Here is another simple function to check sanity of MAC address

    #include 
    #include 
    
    typedef unsigned char byte;
    
    #define ETH_ADDR_LEN    6
    #define FALSE           0
    #define TRUE            1
    #define MAC_STR_LEN     18
    #define SEPERATOR       ':'
    
    int isMacValid(char *MacAddress) {
        char mac_part[3] = {0};
        byte mac_byte    = 0;
        byte mac_idx     = 0;
    
        while(MacAddress[mac_idx] != 0 && mac_idx < MAC_STR_LEN){
            if(mac_idx != 15 && MacAddress[mac_idx + 2] != SEPERATOR)
                return FALSE;
            strncpy(mac_part, MacAddress+mac_idx,2);
            mac_byte = (byte)strtol(mac_part, NULL, 16);
            if(mac_byte == 0 && strcmp(mac_part,"00"))
                return FALSE;
            mac_idx += 3;
        }
    
        if(mac_idx == MAC_STR_LEN)
            return TRUE;
        return FALSE;
    }
    

提交回复
热议问题