2

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
2
  • 1
    fgets will store any trailing newline character, \n. Maybe that is confusing the ioctl call? Commented Jun 20, 2020 at 4:57
  • @kaylum, thank you that works..!!! Edited the post with your answer. Commented Jun 20, 2020 at 5:06

1 Answer 1

3

From the fgets manual:

If a newline is read, it is stored into the buffer

So interface may contain the trailing newline which would confuse the ioctl. Use any method to first strip the \n before passing to ioctl. For example:

if ((p=strchr(interface, '\n')) != NULL) {
    *p = '\0';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.