我想讀取我的目標的MAC地址。所以我用下面的代碼C閱讀mac地址 - 未定義的行爲
TS32 get_mac_address(TU8 ** aps8Mac)
{
TS32 fd;
struct ifreq ifr;
CHAR *iface = "eth0";
TU8 *mac;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
*aps8Mac = mac;
return 0;
}
int main(int argc, char **argv)
{
TU8 *s8Mac = NULL;
get_mac_address(&s8Mac);
fprintf(stdout, "MAC address : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , s8Mac[0], s8Mac[1], s8Mac[2], s8Mac[3], s8Mac[4], s8Mac[5]);
fprintf(stdout, "MAC address : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , s8Mac[0], s8Mac[1], s8Mac[2], s8Mac[3], s8Mac[4], s8Mac[5]);
return 0;
}
在我收到的目標一旦執行:
MAC address : 00:1A:02:5F:00:76
MAC address : FE:76:9C:8C:AB:7E
爲什麼我不讀
MAC address : 00:1A:02:5F:00:76
MAC address : 00:1A:02:5F:00:76
編輯1: get_mac_address關於改性給出的建議爲答案
TS32 get_mac_address(TU8 ** aps8Mac)
{
TS32 fd;
struct ifreq ifr;
CHAR *iface = "eth0";
TU8 *mac = malloc(sizeof(TU8) * 17);
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
mac = (TU8 *)ifr.ifr_hwaddr.sa_data;
*aps8Mac = mac;
return 0;
}
在哪裏你是否分配空間來保存MAC地址? –
@DavidSchwartz我修改了主題以包含修改的功能。但是,我仍然獲得相同的行爲 – ogs
您丟棄從'malloc'獲得的值並仍然返回一個臨時指針。 'mac =(TU8 *)ifr.ifr_hwaddr.sa_data; * aps8Mac = mac;'只是設置'* aps8Mac'等於'ifr.ifr_hwaddr.sa_data'的迂迴路線。 –