在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();
注意事項: