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

前端 未结 4 594
挽巷
挽巷 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:05

    You can rely on the sscanf to check the format and content of the provided MAC address, something like

    bool checkMacAddr(const char * mac) noexcept
    {
        if(nullptr == mac) return false;
        printf("[%s] strlen(%s)=%lu\n", __func__, mac, strlen(mac));
        if(strlen(mac) != 17) return false;
    
        uint32_t bytes[6]={0};
    
        return (6 == sscanf(mac, "%02X:%02X:%02X:%02X:%02X:%02X"
                , &bytes[5]
                , &bytes[4]
                , &bytes[3]
                , &bytes[2]
                , &bytes[1]
                , &bytes[0]));
    }
    

提交回复
热议问题