C : 如何复制 char 数组到 struct ifreq?
C : How to copy char array to struct ifreq?
无法将 char 数组复制到 struct ifreq s。下面是定义好的声明,
#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] = '[=10=]';
printf("reader_mac ::: %s\n",reader_mac);
}
}
现在,在将接口复制到 s.ifr_name 时,我无法检索给定接口的 mac 地址,而如果我将 strcpy(s.ifr_name, interface) 替换为 strcpy( s.ifr_name,"wlp1s0"),同样是能够return的mac地址。
我可以使用系统命令检索活动的网络接口,
interface :: wlp1s0
然而,检索到的网络接口被传递给 strcpy() 以将接口复制到 s.ifr_name,我无法检索到 mac 地址。
这里必须如何解决这个问题?
kaylum 来自评论的建议:
加入后strtok(interface, "\n");在上面的脚本中,它无法检索 mac 地址。
reader_mac ::: fc017c0f2b75
来自fgets
manual:
If a newline is read, it is stored into the buffer
所以 interface
可能包含尾随的换行符,这会混淆 ioctl
。使用任何方法在传递给 ioctl.
之前首先去除 \n
例如:
if ((p=strchr(interface, '\n')) != NULL) {
*p = '[=10=]';
}
无法将 char 数组复制到 struct ifreq s。下面是定义好的声明,
#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] = '[=10=]';
printf("reader_mac ::: %s\n",reader_mac);
}
}
现在,在将接口复制到 s.ifr_name 时,我无法检索给定接口的 mac 地址,而如果我将 strcpy(s.ifr_name, interface) 替换为 strcpy( s.ifr_name,"wlp1s0"),同样是能够return的mac地址。
我可以使用系统命令检索活动的网络接口,
interface :: wlp1s0
然而,检索到的网络接口被传递给 strcpy() 以将接口复制到 s.ifr_name,我无法检索到 mac 地址。
这里必须如何解决这个问题?
kaylum 来自评论的建议:
加入后strtok(interface, "\n");在上面的脚本中,它无法检索 mac 地址。
reader_mac ::: fc017c0f2b75
来自fgets
manual:
If a newline is read, it is stored into the buffer
所以 interface
可能包含尾随的换行符,这会混淆 ioctl
。使用任何方法在传递给 ioctl.
之前首先去除 \n
例如:
if ((p=strchr(interface, '\n')) != NULL) {
*p = '[=10=]';
}