Reputation: 1058
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?
Upvotes: 1
Views: 241
Reputation: 842
you cannot point to a stack space to return in a function.
Instead, you can malloc a heap space to store the result you wanted:
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*) malloc(sizeof(buffer.ifr_hwaddr.sa_data));
memcpy(*address, buffer.ifr_hwaddr.sa_data,sizeof(buffer.ifr_hwaddr.sa_data));
//for (s = 0; s < 6; s++)
//{
// printf("%.2X ", *(*address + s));
//}
//printf("\n");
}
BTW, don't forget to free the heap space in your main function.
Upvotes: 1
Reputation: 2211
If you want to fix it...
//*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
*address = malloc (strlen (buffer.ifr_hwaddr.sa_data) + 1);
strcpy (*address, buffer.ifr_hwaddr.sa_data);
Upvotes: 2
Reputation: 141574
Problem is here:
*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
buffer
is a local variable to your function. So the pointer you are storing in address
points to a local variable which is destroyed when the function returns, leaving a dangling pointer.
Trying to read from this pointer causes undefined behaviour. Your output can be explained depending on whether the memory was re-used for something else already by the time you did the print or not.
Upvotes: 3