MAC Address printing

后端 未结 4 681
北海茫月
北海茫月 2021-01-12 10:06

This is a code that gets some info about network the problem is when it prints the MAC address it prints it sometime normally and sometime with fff\'s like 00:21:84:a2:12:88

4条回答
  •  甜味超标
    2021-01-12 10:38

    Although there is already an accepted answer here, there is a better solution in netinet/ether.h.

    Given that Mac addresses are typically stored in u_int8_t types, as in the ether_addr struct:

    You can simply do this:

    printf("Mac Address: %s", ether_ntoa((struct ether_addr*)ar->sa));
    

    in my Case ar is something that looks like this:

    struct {
       u_int8_t sa[6];
    }
    

    You can easily copy this into another buffer with something like asprintf:

    char *formatted_mac_address;
    asprintf(formatted_mac_address, "Mac Address: %s", ether_ntoa((struct ether_addr*)ar->sa));
    

    If you don't have a struct as I do, you can also just use the address of any u_int8_t in place of ar->sa.

    Appropriate headers/etc should be pulled in, but that's going to look a lot neater than the accepted solution here.

提交回复
热议问题