2011-06-07 58 views
0

我想將Linux中的ARP表格轉換爲下面列出的代碼的數組。我總是得到變量ip和mac中的地址,但是當分配給數組時,它只顯示一些瘋狂的數字。我做錯了什麼? (我不能熟練編程)如何從文件中獲取ARP綁定到數組

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); 
    } 

回答

0

你需要修復您的結構,使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表有一個標題,所以你需要放棄第一行。

+0

太棒了!謝謝! – shaggy 2011-06-07 11:45:07

+0

什麼是ARP_table_vel變量?我如何獲得arp表中的行數以確定ARP_Table大小? – 2015-10-26 07:15:51

相關問題