C++中<ws2tcpip.h>库getnameinfo()未声明等编译错误求助
解决Windows下TCP服务器代码中getnameinfo和inet_ntop未声明的编译错误
你遇到的编译错误是因为Windows的Winsock头文件默认未暴露getnameinfo和inet_ntop这两个POSIX标准网络函数的声明,需要通过定义特定宏来启用它们。
解决步骤
在所有头文件包含语句之前,添加_WIN32_WINNT宏定义,指定目标Windows版本(推荐0x0600及以上,对应Windows Vista及后续系统):
#define _WIN32_WINNT 0x0600 #include <iostream> #include <ws2tcpip.h> #pragma comment (lib, "ws2_32.lib") using namespace std;
原因说明
Windows的ws2tcpip.h头文件中,getnameinfo和inet_ntop的声明被包裹在条件编译块中,只有当_WIN32_WINNT宏定义的值不低于0x0600时,才会暴露这些函数的声明,否则编译器无法识别它们。
修改后的完整代码
#define _WIN32_WINNT 0x0600 #include <iostream> #include <ws2tcpip.h> #pragma comment (lib, "ws2_32.lib") using namespace std; int main () { // Initialisation de Winsock WSADATA wsData; WORD ver = MAKEWORD(2,2); int wsOk = WSAStartup(ver, &wsData); if (wsOk != 0) { std::cerr << "Can't Initialize winsock! Quitting" << std::endl; return 1; } // Création de la socket SOCKET listening = socket (AF_INET, SOCK_STREAM, 0); if (listening == INVALID_SOCKET) { cerr << "On ne peut pas créer de socker... Fermeture !" << endl; return 1; } // Adresse IP sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons(54000); hint.sin_addr.S_un.S_addr = INADDR_ANY; bind(listening, (sockaddr*)&hint, sizeof(hint)); // Socket à l'écoute listen(listening, SOMAXCONN); // Attente de connexion sockaddr_in client; int clientSize = sizeof(client); SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize); char host[NI_MAXHOST]; char service[NI_MAXSERV]; ZeroMemory(host, NI_MAXHOST); ZeroMemory(service, NI_MAXSERV); if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) { cout << host << " Connecté au port " << service << endl; } else { inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST); cout << host << " Connecté au port " << ntohs(client.sin_port) << endl; } // Fermeture de l'ecoute de la socket closesocket(listening); // Boucle While : Accepte et affiche le message du client char buf[4096]; while(true) { ZeroMemory(buf, 4096); // Attente que le client envoi les données int bytesReceivied = recv(clientSocket, buf, 4096, 0); if (bytesReceivied == SOCKET_ERROR) { cerr << " Erreur dans le recv()... Fermeture !" << endl; break; } if (bytesReceivied == 0) { cout << " Client deconnecté " << endl; break; } send(clientSocket, buf, bytesReceivied + 1, 0); } closesocket(clientSocket); WSACleanup(); return 0; }
内容的提问来源于stack exchange,提问作者Rabah
相关产品推荐
相关产品推荐

