#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>int main() {struct addrinfo hints, *res, *p;int status;char ipstr[INET6_ADDRSTRLEN];// 设置hints结构体,指定我们想要获取的地址类型memset(&hints, 0, sizeof hints);hints.ai_family = AF_UNSPEC; // AF_INET 或 AF_INET6 以获取 IPv4 或 IPv6 地址hints.ai_socktype = SOCK_STREAM; // TCP 流套接字// 获取地址信息if ((status = getaddrinfo("www.baidu.com", NULL, &hints, &res)) != 0) {fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));return 1;}printf("IP addresses for www.baidu.com:\n\n");// 遍历所有获取到的地址for(p = res; p != NULL; p = p->ai_next) {void *addr;char *ipver;// 获取IP地址if (p->ai_family == AF_INET) { // IPv4struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;addr = &(ipv4->sin_addr);ipver = "IPv4";} else { // IPv6struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;addr = &(ipv6->sin6_addr);ipver = "IPv6";}// 将IP地址转换为字符串inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);printf("%s: %s\n", ipver, ipstr);}// 释放addrinfo结构体freeaddrinfo(res);return 0;
}