Skip to content

Instantly share code, notes, and snippets.

@dhilst
Created July 9, 2016 03:38
Show Gist options
  • Save dhilst/ff0ce6f7f1f49a89acb23650868dcfc1 to your computer and use it in GitHub Desktop.
Save dhilst/ff0ce6f7f1f49a89acb23650868dcfc1 to your computer and use it in GitHub Desktop.
parse_macaddr
#include <string.h>
#include <stdio.h>
static unsigned char b[6];
#include <assert.h>
#if !defined(__KERNEL__)
#define BUG_ON(cond) assert(!(cond))
#endif
void parse_macaddr(unsigned char b[6], const char *s)
{
const char *ptr = s;
int pos = 0;
do {
char tmp;
char tmpstr[3];
sscanf(ptr, "%3[0-9a-z]", &tmpstr);
sscanf(tmpstr, "%02hhx", &tmp);
BUG_ON(!(tmpstr[0] >= '0' && tmpstr[0] <= '9' ||
tmpstr[0] >= 'a' && tmpstr[0] <= 'f'));
BUG_ON(!(tmpstr[1] >= '0' && tmpstr[1] <= '9' ||
tmpstr[1] >= 'a' && tmpstr[1] <= 'f'));
BUG_ON(pos >= 6);
b[pos++] = tmp;
ptr = strchr(ptr+1, ':');
if (ptr) ptr++;
} while (ptr);
}
int main(int argc, char **argv)
{
assert(argc > 1);
parse_macaddr(b, argv[1]);
int i;
for (i = 0; i < sizeof(b); i++)
printf("%02x:", b[i]);
putchar('\n');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment