2012-03-27 25 views
0

我看到了一個獲取接口的mac和ipv4地址的示例代碼。我改了一點試圖讓該接口,但該方案的IPv6地址失敗說「27:13:錯誤:分配給從類型類型‘u_int32_t’時,不兼容的類型「結構libnet_in6_addr」如何使用libnet獲取接口的ipv6地址?

#include <stdlib.h> 
#include <libnet.h> 
#include <stdint.h> 

int main() { 

    libnet_t *l; /* libnet context */ 
    char errbuf[LIBNET_ERRBUF_SIZE]; 
    u_int32_t ip_addr; 
    struct libnet_ether_addr *mac_addr; 

    l = libnet_init(LIBNET_RAW4, NULL, errbuf); 
    if (l == NULL) { 
    fprintf(stderr, "libnet_init() failed: %s\n", errbuf); 
    exit(EXIT_FAILURE); 
    } 

    ip_addr = libnet_get_ipaddr4(l); 
    if (ip_addr != -1) 
    printf("IP address: %s\n", libnet_addr2name4(ip_addr,\ 
          LIBNET_DONT_RESOLVE)); 
    else 
    fprintf(stderr, "Couldn't get own IP address: %s\n",\ 
        libnet_geterror(l)); 

    u_int32_t ipv6_addr; 
    ipv6_addr = libnet_get_ipaddr6(l); 
    if (ip_addr != -1) 
    printf("IPv6 address: %s\n", libnet_addr2name6(ip_addr,\ 
          LIBNET_DONT_RESOLVE)); 
    else 
    fprintf(stderr, "Couldn't get own IPv6 address: %s\n",\ 
        libnet_geterror(l)); 

    mac_addr = libnet_get_hwaddr(l); 
    if (mac_addr != NULL) 
    printf("MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n",\ 
     mac_addr->ether_addr_octet[0],\ 
     mac_addr->ether_addr_octet[1],\ 
     mac_addr->ether_addr_octet[2],\ 
     mac_addr->ether_addr_octet[3],\ 
     mac_addr->ether_addr_octet[4],\ 
     mac_addr->ether_addr_octet[5]); 
    else 
    fprintf(stderr, "Couldn't get own MAC address: %s\n",\ 
        libnet_geterror(l)); 

    libnet_destroy(l); 
    return 0; 
} 

我不不知道用什麼來存儲ipv6地址,所以我使用u_int32_t,我試過u_int64_t它不起作用。我想知道如果再次遇到這樣的基本問題,我應該在哪裏找到解決方案。我找不到有關ipv6地址的示例。

回答

0

首先,我不知道libnet。

也就是說,可以從您的代碼中導出答案。

如果

u_int32_t ipv6_addr; 
ipv6_addr = libnet_get_ipaddr6(l); 

失敗

error: incompatible types when assigning to type ‘u_int32_t’ from type ‘struct libnet_in6_addr’ 

,可以說ipv6_addr應該有類型struct libnet_in6_addr

此外,

if (ip_addr != -1) 
    printf("IPv6 address: %s\n", libnet_addr2name6(ip_addr,\ 
         LIBNET_DONT_RESOLVE)); 

應由

  • 替換ip_addrip_addr6
  • 改變(ip_addr != -1)到任何的libnet其文檔中建議改變。

爲了知道是否找到了IPv6地址。

順便說一句:可能有更多的IPv6地址。