簡體   English   中英

您如何驗證字符串是C中的有效MAC地址?

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

例:

12:45:ff:ab:aa:cd    is valid
45:jj:jj:kk:ui>cd    is not valid

以下代碼檢查有效的MAC地址(帶或不帶“:”分隔符):

#include <ctype.h>

int isValidMacAddress(const char* mac) {
    int i = 0;
    int s = 0;

    while (*mac) {
       if (isxdigit(*mac)) {
          i++;
       }
       else if (*mac == ':' || *mac == '-') {

          if (i == 0 || i / 2 - 1 != s)
            break;

          ++s;
       }
       else {
           s = -1;
       }


       ++mac;
    }

    return (i == 12 && (s == 5 || s == 0));
}

該代碼檢查以下內容:

  • 輸入字符串mac恰好包含12個十六進制數字。
  • 也就是說,如果在輸入字符串中出現分隔符冒號: ,則僅在偶數個十六進制數字之后出現。

它是這樣的:

  • imac的十六進制數字)被初始化為0。
  • while循環輸入字符串中的每個字符,直到字符串結尾或檢測到12個十六進制數字。
    • 如果當前字符( *mac )是有效的十六進制數字,則i遞增,並且循環將檢查下一個字符。
    • 否則,循環檢查當前字符是否為分隔符(冒號或破折號); 如果是這樣,它將驗證每對十六進制數字是否有一個分隔符。 否則,循環將中止。
  • 循環結束后,該函數檢查是否找到了12個十六進制數字,以及零個或恰好五個分隔符,並返回結果。

如果您不想接受分隔符,只需將return語句更改為:

return (i == 12 && s == 0);

我需要在ANSI C中驗證和解析MAC地址,所以這里是函數。 如果mac地址已經過驗證,則返回1(它將接受12個十六進制字符,小寫或大寫字母,帶或不帶冒號,包括部分正確的輸入,如b3:0a:23:48fad3 )。 它在cortex m3控制器上的嵌入式應用程序中為我完成了工作。
該功能還將接受來自網頁的直接輸入(這實際上是我的用法),因此它將接受冒號作為%3A字符。
結果是一個六個字節的數組。 您必須為此#include <cctype>
輸入字符串( *mac )必須以零結尾,函數才能正常工作。

int parse_mac_address(char* mac, unsigned char *mac_address) {
int index=0;
char temp_mac[12]={0,0,0,0,0,0,0,0,0,0,0,0};

memset(mac_address, 0, 6);              // Clear the 6 needed bytes in target array (which should be defined as "unsigned char mac_address[6]")

while(*mac) {                           // Repeat while we have something in the string
    if(index>11) {                      // The string may be longer than our 12 digits
        return 0;                       // If it has too many digits, break out and return an error (zero)
    }

    if(isxdigit(*mac)) {                // If this is a hex digit
        if(isdigit(*mac)) {             // If the digit is 0 to 9
            temp_mac[index]=*mac-0x30;  // Convert to a number
        }
        else {                          // If the digit is A to F
            temp_mac[index]=toupper(*mac)-0x37; // Make sure it is an upper case letter and convert to a number
        }
        ++mac;                          // Go further on the mac string
        ++index;                        // Promote the index to the next value in our array
    }
    else {
        if(!(index%2) && *mac==':') {   // If it was not a digit, it can be a colon, but only on an odd locations in the array
            ++mac;
        }
        else {
            if(!(index%2) && *mac=='%' && *(mac+1)=='3' && toupper(*(mac+2))=='A') { // In case of web colon sign we receive '%3A' instead, so we have to jump 3 characters to the next digit
                mac+=3; 
            }
            else {                      // If we discovered anything else, this is not a valid mac address - break out and return an error (zero)
                return 0;
            }
        }
    }
}

if(index!=11) {                         // Last check - the index must be exactly 11, to indicate we have filled in 12 digits
    return 0;                           // If not - return with error (zero)
}

for(index=0;index<6;index++) {          // Now, when we have 12 digits in an array, we will convert them in to two-digit bytes
    *(mac_address+5-index)=temp_mac[index*2+1]+temp_mac[index*2]*0x10; // Taking pairs of digits and converting them in to a byte
    // This operation will make mac_address[0] the LSB and mac_address[5] the MSB
    // If you need it the other way round, replace *(mac_address+5-index) with *(mac_address+index)
}

return 1;                               // Return OK (one)
}

這是檢查MAC地址是否正常的另一個簡單功能

#include <stdio.h>
#include <string.h>

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;
}

您可以依靠sscanf來檢查所提供的MAC地址的格式和內容,例如

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]));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM