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


example:

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

the following code checks valid mac addresses (with or w/o ":" separator):

#include <ctype.h>  int isvalidmacaddress(const char* mac) {     int = 0;     int s = 0;      while (*mac) {        if (isxdigit(*mac)) {           i++;        }        else if (*mac == ':' || *mac == '-') {            if (i == 0 || / 2 - 1 != s)             break;            ++s;        }        else {            s = -1;        }          ++mac;     }      return (i == 12 && (s == 5 || s == 0)); } 

the code checks following:

  • that input string mac contains 12 hexadecimal digits.
  • that, if separator colon : appears in input string, appears after number of hex digits.

it works this:

  • i,which number of hex digits in mac, initialized 0.
  • the while loops on every character in input string until either string ends, or 12 hex digits have been detected.
    • if current character (*mac) valid hex digit, i incremented, , loop examines next character.
    • otherwise, loop checks if current character separator (colon or dash); if so, verifies there 1 separator every pair of hex digits. otherwise, loop aborted.
  • after loop finishes, function checks if 12 hex digits have been found, , 0 or 5 separators, , returns result.

if don't want accept separators, change return statement to:

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

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -