在Windows下,可以使用Winsock库来实现与netdb.h头文件相似的功能。具体步骤如下:
#include <winsock2.h>
#include <ws2tcpip.h>
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("Failed to initialize Winsock\n");
return -1;
}
struct addrinfo hints;
struct addrinfo *result;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP socket
hints.ai_protocol = IPPROTO_TCP; // TCP protocol
int ret = getaddrinfo("www.example.com", "http", &hints, &result);
if (ret != 0) {
printf("getaddrinfo failed: %d\n", ret);
WSACleanup();
return -1;
}
// 遍历结果
struct addrinfo *ptr = result;
while (ptr != NULL) {
// 可以在这里访问ptr->ai_addr等结构体成员获取具体信息
ptr = ptr->ai_next;
}
freeaddrinfo(result);
WSACleanup();
注意事项: