欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux下 C语言 获取网卡信息:网卡名字 ipv4 ipv6。

程序员文章站 2022-06-03 08:42:06
...

#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;
  struct sockaddr_in *sa4;
  char addr[INET6_ADDRSTRLEN];
  char addr4[INET_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);
    } else if(ifa->ifa_addr->sa_family == AF_INET){
		sa4 = (struct sockaddr_in *)ifa->ifa_addr;
		getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), addr4,
                  sizeof(addr4), NULL, 0, NI_NUMERICHOST);
		/*inet_ntop(AF_INET, sa4, addr4, INET_ADDRSTRLEN);*/
		 printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr4);
	}
  }

  freeifaddrs(ifap);
  return 0;
}


相关标签: c语言