为什么这个 WinSock 代码没有连接到客户端?

Why this WinSock code is not connecting to client?

我是 Winsock 编程的新手,在阅读本书 "Network Programming For Microsoft Windows " 时偶然发现了这段代码。但似乎这段代码无法连接到客户端。请告诉我如何解决这个问题。

我的服务器代码:

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <ws2tcpip.h>

#pragma comment(lib, "Ws2_32.lib")

using namespace std;

int main(){
    WSADATA wsadata;
    int ret;
    if ((ret = WSAStartup(MAKEWORD(2, 2), &wsadata)) != 0){
        cout << "Wsastartup failed" << endl;
    }
    else{
        cout << "connection made successfully" << endl;
    }

    SOCKET ListeningSocket, NewConnection;
    SOCKADDR_IN ServerAddr, ClientAddr;
    int port = 80;

    ListeningSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    ServerAddr.sin_family = AF_INET;
    ServerAddr.sin_port = htons(port);
    inet_pton(ServerAddr.sin_family,"127.0.0.1",&ServerAddr.sin_addr.s_addr);
    int res= bind(ListeningSocket,(SOCKADDR*)&ServerAddr,sizeof(ServerAddr));
    if (res == SOCKET_ERROR){
        cout << "binding failed" << endl;
    }
    res = listen(ListeningSocket,5);
    if (res == SOCKET_ERROR){
        cout << "Listening failed" << endl;
    }
    int c = 1;
    NewConnection=  accept(ListeningSocket,(SOCKADDR*)&ClientAddr,&c);
    if (NewConnection == INVALID_SOCKET){
cout << "COULD not CONNECT TO CLIENT . err code : "<<WSAGetLastError()  << endl;
    }


    closesocket(ListeningSocket);
    if (WSACleanup() == SOCKET_ERROR){
        cout << "WSACleanup failed with error : " << WSAGetLastError() << endl;
    }
    else{
        cout << "WinSock data cleaned successfully" << endl;
    }
cin.get();
}

在 运行 这段代码中,它显示 "COULD not CONNECT TO CLIENT. err code 10014" 。 我在 windows 开发中心找到了这个错误代码的描述: 地址错误。

系统在尝试使用调用的指针参数时检测到无效的指针地址。如果应用程序传递了无效的指针值,或者缓冲区的长度太小,则会发生此错误。例如,如果参数的长度是 sockaddr 结构,小于 sizeof(sockaddr).

我该如何解决这个错误?

当你调用accept时,第三个参数指向的变量需要保存第二个参数指向的缓冲区的大小。 (当acceptreturns时,会持有space实际使用的数量)

在您的代码中,更改:

int c = 1;

int c = sizeof(ClientAddr);