samedi 21 décembre 2019

win32 socket bind func fails with error 10014 c++

I am trying to run a tcp server on my machine, this is mostly a tutorial code but for some reason the bind is failing with error 10014. sizeof(serverAddr) returns 16 in the below code if anyone is interested. I know what error 10014 means but can't seem to figure out why it's coming here on bind everything seems ok.

#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"Ws2_32.lib")


int main()
{
    WSADATA WSAData;

    SOCKET server, client;

    SOCKADDR_IN serverAddr, clientAddr;

    int iResult = WSAStartup(MAKEWORD(2, 2), &WSAData);
    if (iResult != NO_ERROR) {
        std::cout << "startup error" << std::endl;
        return 1;
    }
    server = socket(AF_INET, SOCK_STREAM, 0);

    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(5555);


    if (bind(server, (SOCKADDR*)&serverAddr, sizeof(serverAddr) != 0))
    {
        std::cout << "bind " << WSAGetLastError() << " sizeof " << sizeof(serverAddr) << std::endl;
        std::cout << "cannot start server" << std::endl;
        return 0;
    }
    listen(server, 0);

    std::cout << "Listening for incoming connections..." << std::endl;

    char buffer[1024];
    int clientAddrSize = sizeof(clientAddr);
    if ((client = accept(server, (SOCKADDR*)&clientAddr, &clientAddrSize)) != INVALID_SOCKET)
    {
        std::cout << "Client connected!" << std::endl;
        recv(client, buffer, sizeof(buffer), 0);
        std::cout << "Client says: " << buffer << std::endl;
        memset(buffer, 0, sizeof(buffer));

        closesocket(client);
        std::cout << "Client disconnected." << std::endl;
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire