我是Winsock编程的新手,在阅读“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();
}
运行此代码时,它显示“可能无法连接到客户端。错误代码10014”。 我在Windows开发中心找到了这个错误代码的描述: 地址不好。
系统在尝试使用调用的指针参数时检测到无效指针地址。如果应用程序传递无效指针值,或者缓冲区的长度太小,则会发生此错误。例如,如果参数的长度(sockaddr
结构)小于sizeof(sockaddr).
如何修复此错误?
答案 0 :(得分:1)
当您调用accept
时,第三个参数指向的变量需要保存第二个参数指向的缓冲区大小。 (当accept
返回时,它将保留实际使用的空间量)
在您的代码中,更改:
int c = 1;
到
int c = sizeof(ClientAddr);