How to get ARP bindings from the file into array
I am trying to get the ARP table in Linux to an array with code posted below. I always get the addresses in the variables ip and mac, but when assigning to the array, it just shows some crazy numbers. Am I doing sth wrong? (I am not really skilled in programming)
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], out开发者_如何学Cput[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);
}
You need to fix your structure and make the char
variables into char
arrays:
struct ARP_entry
{
char IPaddr[16];
char MACaddr[18];
char ARPstatus;
int timec;
};
Then you need to do proper copies of the data so you can preserve them:
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++;
}
Finally, the ARP table has a header, so you'll need to discard the first row.
精彩评论