我正在尝试将 Linux 中的 ARP 表获取到一个数组,代码如下。我总是在变量 ip 和 mac 中获取地址,但是当分配给数组时,它只是显示一些疯狂的数字。我做错了什么吗? (我不太擅长编程)
struct ARP_entry
{
char IPaddr;
char MACaddr;
char ARPstatus;
int timec;
};
static struct ARP_entry ARP_table[ARP_table_vel];
void getARP()
{
int i=0;
const char filename[] = "/proc/net/arp";
char ip[16], mac[18], output[128];
FILE *file = fopen(filename, "r");
if ( file )
{
char line [ BUFSIZ ];
fgets(line, sizeof line, file);
while ( fgets(line, sizeof line, file) )
{
char a,b,c,d;
if ( sscanf(line, "%s %s %s %s %s %s", &ip, &a, &b, &mac, &c, &d) < 10 )
{
if ( ARP_table_vel > i)
{
ARP_table[i].IPaddr = ip;
ARP_table[i].MACaddr = mac;
ARP_table[i].ARPstatus = STATUS_CON;
i++;
}
}
}
}
else
{
perror(filename);
}
最佳答案
您需要修复结构并将 char
变量放入 char
数组中:
struct ARP_entry
{
char IPaddr[16];
char MACaddr[18];
char ARPstatus;
int timec;
};
然后您需要对数据进行适当的复制,以便保留它们:
if ( ARP_table_vel > i)
{
snprintf(ARP_table[i].IPaddr, 16, "%s", ip);
snprintf(ARP_table[i].MACaddr, 18, "%s", mac);
ARP_table[i].ARPstatus = STATUS_CON;
i++;
}
最后,ARP 表有一个 header ,因此您需要丢弃第一行。
关于c - 如何将 ARP 绑定(bind)从文件获取到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6264313/