c++socketswinsock2

WSAGetLastErrror returns 0


I'm creating a project using winsock2's sockets I'm using a syscall to connect to a socket on a local IP address, then I implemented a simple method for error handling purposes.

// Client-side
int LPTF_SOCKET::connectLPTFSocket()
{
  if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
  {
    std::cerr << "Connection failed: " << WSAGetLastError() << std::endl;
    closesocket(sockfd);
    WSACleanup();
    return 1;
  }
  std::cerr << "connect returned success" << std::endl;
  return 0;
}

However, whenever an error occurs, my project partners get the code 10047. It is fixed since then, but I always get error 0, which is weird since it doesn't appear on the official documentation

The thing is, this error code appears on both of my computers, so that makes it even stranger. I thought at first it might be due to the firewall, but I'm not sure. Do you guys have a clue of what's going on? I can't work on the project anymore

I tried to run the program server-side. It works perfectly, but not for the client-side.

Edit: Also, here's how I set the server up :

// Server/src/main.cpp
LPTF_SOCKET serverSocket;
serverSocket.setUpServiceServer("0.0.0.0", 12345, true);

// Common/src/LPTF_Socket.cpp
void LPTF_SOCKET::setUpServiceServer(const std::string &ip, int port, bool isServer)
{
   service.sin_family = AF_INET;
   service.sin_port = htons(port);

   if (isServer)
   {
       service.sin_addr.s_addr = INADDR_ANY;
   }
   else
   {
       service.sin_addr.s_addr = inet_addr(ip.c_str());
   }
   memset(service.sin_zero, 0, sizeof(service.sin_zero));
}

Solution

  • A well known misstep is calling GetLastError() for a general Win32 API error in the middle of some other other code that is likely to call other Win32 APIs under the hood and clear the error state. "print" calls being one of them. But that's shouldn't apply to socket errors handled by WSAGetLastError...

    It's possible that the std::cerr call is clearing the winsock error state when it prints "Connection Failed". Surprising, but I wouldn't rule it out.

    Try this adjustment:

      if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
      {
        DWORD lastErr = WSAGetLastError();
        std::cerr << "Connection failed: " << lastError << std::endl;
        closesocket(sockfd);
        WSACleanup();
        return 1;
      }