本文没有使用ioctl 函数,未使用socket ,直接获取本地的所有地址,包括IPv4,IPV6,MAC 地址:
核心函数是:getifaddrs() & freeifaddrs()
代码如下:
#include#include #include #include #include /*------------------------------------------------------------------------------ * NAME : GetInterfaceAddress * DESCRIPTION : * PARAMETERS : 无 * RETURNVALUE : 无 * ERRORS : * NOTES : * * AUTHOR : alex * CREATETIME : 2013年4月20日, 17:44 * MOTIFYTIME : *------------------------------------------------------------------------------ */void GetInterfaceAddress(){ struct ifaddrs *ifaddr, *ifa; int family; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs"); return; } /* Walk through linked list, maintaining head pointer so we can free list later */ for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; switch (family) { case AF_PACKET: { printf("%s address family: %d%s\n", ifa->ifa_name, family, " AF_PACKET"); struct sockaddr_ll *s = (struct sockaddr_ll*) ifa->ifa_addr; for (int i = 0; i < 6; i++) { printf("%s%02X%s", i == 0 ? "\tMAC Address:<" : "", s->sll_addr[i], i < 5 ? ":" : ">\n"); } break; } case AF_INET: { printf("%s address family: %d%s\n", ifa->ifa_name, family, " AF_INET"); struct sockaddr_in *s = (struct sockaddr_in *) ifa->ifa_addr; //char * aip = inet_ntoa(s->sin_addr); char aip[16]; inet_ntop(AF_INET,&s->sin_addr,aip,sizeof(aip)); printf("\tIPv4 Address:<%s>\n", aip); break; } case AF_INET6: { printf("%s address family: %d%s\n", ifa->ifa_name, family, " AF_INET6"); struct sockaddr_in6 *s = (struct sockaddr_in6 *) ifa->ifa_addr; //char * aip = inet_ntoa(s->sin_addr); char aip[40]; inet_ntop(AF_INET6,&s->sin6_addr,aip,sizeof(aip)); printf("\tIPv4 Address:<%s>\n", aip); break; } default: { printf("Unknown address family\n"); break; } } } freeifaddrs(ifaddr);}