【问题标题】:How to get interface's ipv6 address using libnet?如何使用 libnet 获取接口的 ipv6 地址?
【发布时间】:2012-03-27 13:09:58
【问题描述】:

我看到了一个获取接口的mac和ipv4地址的示例代码。我对其进行了一些更改,试图获取该接口的 ipv6 地址,但程序失败说“27:13:错误:从类型‘struct libnet_in6_addr’分配给类型‘u_int32_t’时不兼容的类型”

#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 地址的示例。

【问题讨论】:

    标签: ipv6 libnet


    【解决方案1】:

    首先,我不知道 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_addr 替换为ip_addr6
    • (ip_addr != -1) 更改为 libnet 在其文档中推荐的任何内容。

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

    顺便说一句:可能有超过 1 个 IPv6 地址。

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      相关资源
      最近更新 更多