[英]C : How to copy char array to struct ifreq?
Unable to copy a char array to struct ifreq s.无法将 char 数组复制到 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.现在,在将接口复制到 s.ifr_name 时,我无法检索给定接口的 mac 地址,而如果我将 strcpy(s.ifr_name, interface) 替换为 strcpy(s.ifr_name,"wlp1s0"),同样可以返回mac地址。
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.然而,检索到的网络接口被传递给 strcpy() 以将该接口复制到 s.ifr_name,但我无法检索 mac 地址。
How this has to be addressed here?这里必须如何解决?
kaylum's Suggestion from the comments: kaylum 评论中的建议:
After adding strtok(interface, "\n");添加后 strtok(interface, "\n"); in the above script, it is not able to retrieve the mac address.
在上面的脚本中,它无法检索 mac 地址。
reader_mac ::: fc017c0f2b75
From the fgets
manual :从
fgets
手册:
If a newline is read, it is stored into the buffer
如果读取了换行符,则将其存储到缓冲区中
So interface
may contain the trailing newline which would confuse the ioctl
.因此
interface
可能包含尾随换行符,这会混淆ioctl
。 Use any method to first strip the \n
before passing to ioctl.
使用任何方法在传递给
ioctl.
之前先去除\n
。 For example:例如:
if ((p=strchr(interface, '\n')) != NULL) {
*p = '\0';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.