0

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

Ram
  • 3,045
  • 3
  • 27
  • 42
  • 1
    Use `\n` for a newline instead of `/n`. The code also runs fine on my system, what is the exact issue you're having? – DutChen18 Mar 03 '20 at 10:16
  • I am not able to create the socket and I get a SOCKET_ERROR – Ram Mar 03 '20 at 10:19
  • 1
    Try using `perror()` or `strerror()` to output some more info about the error. – G.M. Mar 03 '20 at 10:21
  • 2
    I think you should check `WSAGetLastError()` to figure out the details about the error. Also, according to the docs at https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket the function returns `INVALID_SOCKET` on error ( not `SOCKET_ERROR`). – Daniel Junglas Mar 03 '20 at 10:22
  • 2
    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; } – Sanjeev Mar 03 '20 at 10:35

1 Answers1

3

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; 
}
Sanjeev
  • 348
  • 2
  • 9