c++winsockets

Porting to windows sockets


I am trying to port some legacy code and noticed few problems.

I have isolated the code for a simple example. What is wrong with the socket creation code below?

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

int main()
{
    std::cout << "Hello World!\n";
    sockaddr_in sockAddr;
    uint16_t PortNumber = 2000;
    memset(&sockAddr, 0, sizeof(sockAddr));
    sockAddr.sin_family = AF_INET;
    sockAddr.sin_port = htons(PortNumber);
    sockAddr.sin_addr.s_addr = 0;
    auto result = socket(AF_INET, SOCK_STREAM, 0);

    if (result == INVALID_SOCKET)
    {
        auto err = WSAGetLastError();
        std::cout << "Unable to create listening socket on port " << PortNumber << "with error "  << err;
    }
    else std::cout << "No socket error \n";
}

enter image description here


Solution

  • You need to initialize it first before making any socket call.

    int iResult; 
    // Initialize Winsock 
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData); 
    if (iResult != 0) 
    { 
       printf("WSAStartup failed: %d\n", iResult); 
       return 1; 
    }