Unable to copy a char array to struct ifreq s. Below is the declaration which has been defined,
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
char interface[100];//="wlp1s0";
char reader_mac[13] = {00};
int main()
{
FILE *f = popen("ip addr show | awk '/inet.*brd/{print $NF}'", "r");
while (fgets(interface, 100, f) != NULL) {
}
strtok(interface, "\n"); // kaylum's Suggestion from the comments below
printf( "interface :: %s\n", interface);
pclose(f);
struct ifreq s;
int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
strcpy(s.ifr_name, interface);
// strcpy(s.ifr_name, "wlp1s0");
if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
int i;
for (i = 0; i < 6; ++i){
unsigned char data = s.ifr_addr.sa_data[i];
// printf("ddd:::%02x\n", data );
sprintf(reader_mac+(i*2), "%02x", data);
}
reader_mac[12] = '\0';
printf("reader_mac ::: %s\n",reader_mac);
}
}
Now, while copying the interface to s.ifr_name, I am unable to retrieve the given interface's mac address, whereas if i replace strcpy(s.ifr_name, interface) as strcpy(s.ifr_name,"wlp1s0"), the same is able to return the mac address.
I can able to retrieve the active network interfaces using system command,
interface :: wlp1s0
Whereas, the retrieved network interface is passed to strcpy() to copy the interface to s.ifr_name, I am unable to retrieve the mac address.
How this has to be addressed here?
kaylum's Suggestion from the comments:
After adding strtok(interface, "\n"); in the above script, it is not able to retrieve the mac address.
reader_mac ::: fc017c0f2b75
fgetswill store any trailing newline character,\n. Maybe that is confusing theioctlcall?