I am trying to get Mac address by this code:
void getMacAdress(unsigned char **address)
{
int s;
struct ifreq buffer;
s = socket(PF_INET, SOCK_DGRAM, 0);
memset(&buffer, 0x00, sizeof(buffer));
strcpy(buffer.ifr_name, "eth0");
ioctl(s, SIOCGIFHWADDR, &buffer);
close(s);
*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
for (s = 0; s < 6; s++)
{
printf("%.2X ", *(*address + s));
}
printf("\n");
}
int main(int argc, char *argv[])
{
unsigned char *address;
getMacAdress(&address);
int i;
for (i = 0; i < 6; i++)
{
printf("%.2X ", *(address + i));
}
printf("\n");
return 0;
}
I got a correct result as
08 00 27 0A 4E 98
08 00 27 0A 4E 98
but when I delete printf snippet code in getMacAddress() function it becomes:
void getMacAdress(unsigned char **address)
{
int s;
struct ifreq buffer;
s = socket(PF_INET, SOCK_DGRAM, 0);
memset(&buffer, 0x00, sizeof(buffer));
strcpy(buffer.ifr_name, "eth0");
ioctl(s, SIOCGIFHWADDR, &buffer);
close(s);
*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
printf("\n");
}
I got the wrong result
08 00 00 00 00 00
Can you explain to me why that is and how I can solve this problem?
getMacAdress()into theaddresspassed into it frommain(), and that leads to undefined behaviour. The space is reused and you get what you get (and you're lucky you didn't crash).*addressandstrcpy (*address , buffer.ifr_hwaddr.sa_data)