0

I'm attempting to determine why the following C++ code connects to a server that does not exist.

#include <boost/asio.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
   boost::asio::io_service ioService;
   int attempts = 0;
   while (true)
   {
      boost::system::error_code ec;
      boost::asio::ip::tcp::socket mySocket(ioService);
      mySocket.connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 32768), ec);
      attempts++;
      if (!ec)
      {
         std::cout << "Connection succeeded!? But server shouldn't exist. Attempts: " << attempts << std::endl;
         return 1;
      }
   }

   return 0;
}

It succeeds after 14116 attempts. For some reason, this is consistent across multiple runs. I was initially testing this with port 36110 (And many ports above and below it), but eventually found that my issue occurs for even-numbered ports in the range 32768-60998. I haven't exhaustively tested all the ports within the range.

In order to rule out the issue being C++/Boost-specific, I also used this Python script to test a range of ports (manually), seeing the same result (Although with an attempt count that was seemingly random):

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

attempts = 0
while True:
    ret = clientsocket.connect_ex(('127.0.0.1', 32768))
    attempts += 1
    if ret == 0:
        print(f"Connected after {attempts} attempts")
        break

I have replicated the issue across 5 different Linux machines, with variances including Ubuntu 18.04/20.04, Windows Subsystem for Linux, and native Linux machines. The issue does not occur when running on Windows.

My understanding is that these ports are not necessarily reserved, and so may be free to use. But perhaps I am mistaken?

  • Given that this is Linux question and not a programming question, it would likely be better suited for [Unix & Linux StackExchange](https://unix.stackexchange.com/) – Brian61354270 Jan 17 '23 at 02:46
  • It doesn't occur on macOS either (confirmed on Linux). Might be related to https://stackoverflow.com/questions/11436013/writing-to-a-closed-local-tcp-socket-not-failing – Selcuk Jan 17 '23 at 02:49
  • If you check what it connects from (getpeername) you will realize that connects to itself, i.e. the chosen ephemeral port is the one you connect to. This is a duplicate of several similar questions. – Steffen Ullrich Jan 17 '23 at 05:45

0 Answers0