example:
12:45:ff:ab:aa:cd is valid 45:jj:jj:kk:ui>cd is not valid
The following code checks for valid MAC addresses (with or w/o the ":" separator):
#include
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));
}
The code checks the following:
mac
contains exactly 12 hexadecimal digits.:
appears in the input string, it only appears after an even number of hex digits.It works like this:
i
,which is the number of hex digits in mac
, is initialized to 0.while
loops over every character in the input string until either the string ends, or 12 hex digits have been detected.
*mac
) is a valid hex digit, then i
is incremented, and the loop examines the next character.If you don't want to accept separators, simply change the return statement to:
return (i == 12 && s == 0);