【发布时间】:2013-12-27 18:18:17
【问题描述】:
我正在制作一个小型 IRC 服务器,但我遇到了一个问题;在尝试侦听套接字时,我收到错误 10022(无效参数)。
accept() 上也出现错误,但这是因为套接字未在侦听(我发布的问题是关于此问题)。
我没有包含接受功能,因为我觉得它没有必要并且会添加毫无意义的代码。
#include <iostream>
#include <ws2tcpip.h>
#include <winsock2.h>
#include <thread>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
#define maxConnections 10
class Server
{
struct sockaddr_storage their_addr;
struct addrinfo hints, *res;
struct addrinfo *servinfo;
int status;
SOCKET sock;
public:
void Start(const char *port);
};
void Server::Start(const char *port)
{
WSADATA WSAData;
if (WSAStartup(MAKEWORD(2, 0), &WSAData) != 0)
{
std::cout << "[ERROR]: " << GetLastError() << ".\n";
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
status = getaddrinfo(NULL, port, &hints, &res);
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << "Bad Socket.\n";
}
bind(sock, res->ai_addr, res->ai_addrlen);
错误:
if (listen(sock, maxConnections) == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << " Listening Failed.\n";
}
上面的代码详细说明了socket的创建和绑定,都成功了(虽然不一定对)。包括“NULL”在内的套接字创建可能是问题所在。
谢谢:)
【问题讨论】:
-
你传递给
bind的参数看起来不对——你应该绑定到一个地址和端口。尝试检查该调用的错误返回。 -
无错误 - WSAGetLastError() 返回 0。