C - formatting MAC address

2019-07-16 12:06发布

I am currently working with parsing some MAC addresses. I am given an output that does not include leading zeros (like so).

char* host = "0:25:25:0:25:25";

and I would like to format it like so

char* host = "00:25:25:00:25:25";

What would be the easiest way to go about this?

For those wondering, I am using the libpcap library.

标签: c formatting
2条回答
我想做一个坏孩纸
2楼-- · 2019-07-16 12:29

I may be missing something in the question. Assuming you know it is a valid MAC, and the input string is thus parsable, have you considered something as simple as:

char* host1 = "0:25:25:0:AB:25";
char *host2 = "0:1:02:3:0a:B";
char result[19];
int a,b,c,d,e,f;

// the question sample
if (sscanf(host1, "%x:%x:%x:%x:%x:%x", &a,&b,&c,&d,&e, &f) == 6)
    sprintf(result, "%02X:%02X:%02X:%02X:%02X:%02X", a,b,c,d,e,f);
printf("host1: %s\n", result);

// a more daunting sample
if (sscanf(host2, "%x:%x:%x:%x:%x:%x", &a,&b,&c,&d,&e, &f) == 6)
    sprintf(result, "%02X:%02X:%02X:%02X:%02X:%02X", a,b,c,d,e,f);
printf("host2: %s\n", result);

Output

host1: 00:25:25:00:AB:25
host2: 00:01:02:03:0A:0B

Obviously for the ultra-paranoid you would want to make sure a-f are all < 255, which is probably preferable. The fundamental reasons I prefer this where performance isn't a critical issue are the many things you may not be considering in your question. It handles all of

  1. Lead values of "n:", where n is any hex digit; not just zero. Examples: "5:", "0:"
  2. Mid values of ":n:", again under the same conditions as (1) above. Examples: ":A:", ":0:"
  3. Tail values of ":n". once more, under the same conditions as (1) above. Examples: ":b", ":0"
  4. Hex-digit agnostic when reading; it works with both upper and lower case digit chars.
  5. Most important, does nothing (except upper-case the hex values) if your input string is already properly formatted.
查看更多
萌系小妹纸
3楼-- · 2019-07-16 12:37

Roughly like this: Allocate an output string to hold the reformatted MAC address. Iterate over the input string and use strtok with : delimiter. In each iteration convert the beginning of the string (2 bytes) into a numerical value (e.g., with atoi). If the result < 16 (i.e., < 0x10), set "0" into the output string at current position and the result in hex at the following position; otherwise copy the 2 bytes of input string. Append : to the output string. Continue till end of the input.

查看更多
登录 后发表回答