使用WinSock时遭遇SOCKET_ERROR,请求代码问题排查指导
排查你的WinSock客户端代码问题
我帮你排查了这段基于微软官方文档的WinSock客户端代码,发现了几个关键问题,这应该就是你无法成功运行的原因:
1. 端口参数未正确传入getaddrinfo
你已经定义了DEFAULT_PORT为目标端口"27015",但调用getaddrinfo时第二个端口参数传了NULL,这会导致地址解析时没有包含端口信息,后续的connect调用自然无法找到正确的服务端口。
修复方法:把getaddrinfo调用中的NULL替换为DEFAULT_PORT:
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
2. 确保目标服务器正在运行
客户端要连接的是127.0.0.1:27015的TCP服务,如果没有对应的服务器程序在这个端口监听,connect必然会失败。你可以:
- 运行微软官方配套的WinSock服务器示例代码
- 自己写一个简单的TCP监听程序测试,或者用工具在本地27015端口开启监听
3. 可选的代码优化与调试点
除了功能性问题,还有几个可以优化的地方,方便你后续调试:
- 将
#define DEFAULT_BUFLEN和#define DEFAULT_PORT移到main函数外面,避免局部宏定义的潜在问题,符合C/C++代码规范 - 在
recv成功后,添加代码打印收到的实际内容(记得给缓冲区加终止符避免乱码),方便验证通信是否正常:
if (iResult > 0) { printf("Bytes received: %d\n", iResult); recvbuf[iResult] = '\0'; // 添加终止符 printf("Received content: %s\n", recvbuf); }
修改后的完整代码片段(关键部分已修正)
#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include "stdafx.h" #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #pragma comment(lib, "Ws2_32.lib") #define DEFAULT_BUFLEN 512 #define DEFAULT_PORT "27015" int main() { WSADATA wsaData; SOCKET ConnectSocket = INVALID_SOCKET; struct addrinfo *result = NULL, *ptr = NULL, hints; char *sendbuf = "this is a test"; char recvbuf[DEFAULT_BUFLEN]; int iResult; int recvbuflen = DEFAULT_BUFLEN; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port - 已修复端口参数 iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } // Attempt to connect to an address until one succeeds for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { // Create a SOCKET for connecting to server ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (ConnectSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); WSACleanup(); return 1; } // Connect to server. iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); if (iResult == SOCKET_ERROR) { closesocket(ConnectSocket); ConnectSocket = INVALID_SOCKET; continue; } break; } freeaddrinfo(result); if (ConnectSocket == INVALID_SOCKET) { printf("Unable to connect to server!\n"); WSACleanup(); return 1; } // Send an initial buffer iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0); if (iResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); return 1; } printf("Bytes Sent: %ld\n", iResult); // shutdown the connection since no more data will be sent iResult = shutdown(ConnectSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); return 1; } // Receive until the peer closes the connection - 已添加内容打印 do { iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0); if (iResult > 0) { printf("Bytes received: %d\n", iResult); recvbuf[iResult] = '\0'; printf("Received content: %s\n", recvbuf); } else if (iResult == 0) printf("Connection closed\n"); else printf("recv failed with error: %d\n", WSAGetLastError()); } while (iResult > 0); // cleanup closesocket(ConnectSocket); WSACleanup(); getchar(); return 0; }
内容的提问来源于stack exchange,提问作者qtjCH5pLao6




