开发者

Conversion of Ethernet address to readable form?

开发者 https://www.devze.com 2023-01-26 10:47 出处:网络
struc开发者_StackOverflow中文版t ethernet_header { u_char ether_dhost[ ETHER_ADDR_LEN]; u_char ether_shost[ETHER_ADDR_LEN];
struc开发者_StackOverflow中文版t ethernet_header
{
    u_char ether_dhost[ ETHER_ADDR_LEN];

    u_char ether_shost[ETHER_ADDR_LEN];

    u_short ether_type;
};

for(i = 0;i <6; i++)
  printf("dest ether:%x",ethernet->ether_dhost);

How to print the Ethernet address in proper readable form with spaces after each byte? The o/p I get is in hex. Here Ethernet is the pointer to the structure ethernet_header.


How about:

printf("%02x:%02x:%02x:%02x:%02x:%02x",
    (unsigned)ethernet->ether_dhost[0],
    (unsigned)ethernet->ether_dhost[1],
    (unsigned)ethernet->ether_dhost[2],
    (unsigned)ethernet->ether_dhost[3],
    (unsigned)ethernet->ether_dhost[4],
    (unsigned)ethernet->ether_dhost[5]);


I think the best way would be to use ether_ntoa() which is available on just about any *nix operating system (available in net/ethernet.h). The following works quite well for me.

char *addr;
struct ether_addr host;

memcpy(&host, ethernet->ether_dhost, sizeof(host));
addr = ether_ntoa(&host);


Something like this should do it:

char mac[6 * 2 + 5 + 1];

for(size_t i = 0, pos = 0; i < sizeof ethernet->ether_dhost; i++)
{
  if(i > 0)
   mac[pos++] = ':';
  sprintf(mac + pos, "%02x", (unsigned int) ethernet->ether_dhost[i] & 0xffu);
}

This also inserts colons between each byte, so the output will look like DE:AD:BE:EF:BA:BE which is how MAC addresses are commonly formatted for Ethernet.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号