i'm making a small IRC server, but I've come across a problem; upon trying to listen to the socket, i get error 10022 (Invalid Argument).
The error also appears on accept(), but this is because the socket isn't listening (the problem i'm posting about).
I didn't include the accept function because i feel it isn't necessary and would be adding pointless code.
#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);
Error:
if (listen(sock, maxConnections) == SOCKET_ERROR)
{
std::cout << "[ERROR]: " << WSAGetLastError() << " Listening Failed.\n";
}
The code above details the socket creation and binding, all of which are successful (though not necessarily right). The socket creation including 'NULL' might be the issue.
Thanks :)
bind
look wrong - you should be binding to an address & port. Try checking the error return from that call. – simonc