如何使用IPv6知道C语言为接口的IP地址 [英] How to know the IP address for interfaces in C using IPv6

查看:1061
本文介绍了如何使用IPv6知道C语言为接口的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我想用自己的接口名称我的Linux机器上的所有IP地址的列表,同时使用 IPv6的的IPv4

Suppose I'd like a list of all IP addresses on my Linux machine by their interface names, using both IPv6 and IPv4.

我能找到的最好的建议是使用 getifaddrs()应该支持IPv6 ,同样从POST <一个href=\"http://stackoverflow.com/questions/4139405/how-to-know-ip-address-for-interfaces-in-c\">here.
然而,getifaddrs()使用,它使用结构sockaddr这与IPv6不兼容结构ifaddrs。相反,它应该是一个指向与结构工会in6_addr为好。

The best advice I could find is to use getifaddrs() that should support IPv6, similarly to a post from here. However, the getifaddrs() uses struct ifaddrs which uses struct sockaddr which is incompatible with IPv6. Instead, it should be a pointer to a union with struct in6_addr as well.

这是如何处理的?如何getifaddrs()支持IPv6?是文档过时了吗?

How is this handled? How does getifaddrs() support IPv6? Is the documentation obsolete?

推荐答案

我的C是非常生疏,与载员工会(如结构体sockaddr_in6 )不再适合结构在我的大脑,所以最好的剪切和粘贴的传统我适应 chrisaycock的回答使用则getnameinfo( )来代替,从 getifaddrs一些帮助()手册页(其中有一个更好的例子):

My C is terribly rusty, and structs with members containing unions (like struct sockaddr_in6) no longer fit in my brain, so in the best cut and paste traditions I adapted chrisaycock's answer to use getnameinfo() instead, with some help from the getifaddrs() man page (which has a better example):

#define _GNU_SOURCE    # required for NI_NUMERICHOST
#include <arpa/inet.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <netdb.h>

int main ()
{
  struct ifaddrs *ifap, *ifa;
  struct sockaddr_in6 *sa;
  char addr[INET6_ADDRSTRLEN];

  getifaddrs (&ifap);
  for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
    if (ifa->ifa_addr->sa_family==AF_INET6) {
      sa = (struct sockaddr_in6 *) ifa->ifa_addr;
      getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), addr,
                  sizeof(addr), NULL, 0, NI_NUMERICHOST);
      printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
    }
  }

  freeifaddrs(ifap);
  return 0;
}

我的系统上的输出:

The output on my system:

Interface: lo   Address: ::1
Interface: br0  Address: fdbf:e684:d5fb:6:6e62:6dff:fed1:dfad
Interface: br0  Address: 2001:db8:1f80:81c6:6e62:6dff:fed1:dfad
Interface: br0  Address: fe80::6e62:6dff:fed1:dfad%br0
Interface: virbr1       Address: fe80::5054:ff:fece:bfec%virbr1
Interface: virbr0       Address: fe80::5054:ff:fef9:c92e%virbr0
Interface: virbr2       Address: fe80::5054:ff:fedd:ea18%virbr2
Interface: vnet0        Address: fe80::fc54:ff:fe90:de19%vnet0
Interface: vnet1        Address: fe80::fc54:ff:fede:b69c%vnet1

记住要添加错误检查的一切;它已经从这个例子中省略。

Remember to add error checking to everything; it has been omitted from this example.

这篇关于如何使用IPv6知道C语言为接口的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆