MAC Address printing

后端 未结 4 652
北海茫月
北海茫月 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:24

    Here is a simple C program to find the MAC address of system:

    #include<stdio.h>
    #include<stdlib.h>
    
    int main() {
        system("getmac");
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-12 10:29

    It looks like a signed/unsigned problem.

    Try to cast into unsigned char :

      printf("> Successfully received Local MAC Address : %02x:%02x:%02x:%02x:%02x:%02x\n",
      (unsigned char) ifr.ifr_hwaddr.sa_data[0],
      (unsigned char) ifr.ifr_hwaddr.sa_data[1],
      (unsigned char) ifr.ifr_hwaddr.sa_data[2],
      (unsigned char) ifr.ifr_hwaddr.sa_data[3],
      (unsigned char) ifr.ifr_hwaddr.sa_data[4],
      (unsigned char) ifr.ifr_hwaddr.sa_data[5]);
    
    0 讨论(0)
  • 2021-01-12 10:29

    I prefer use an explicit length modifier in format string for values shorter than int. For example %02hhx instead of %02x for one-byte values. It allow me to not worry about those subtle conversion and promotion issues:

    #include <stdio.h>
    
    int main(void)
    {
        signed char sff = '\xff';
        unsigned char uff = '\xff';
    
        printf("signed:   %02x %02hhx\n", sff, sff);
        printf("unsigned: %02x %02hhx\n", uff, uff);
    
        return 0;
    }
    

    prints

    signed:   ffffffff ff
    unsigned: ff ff
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题