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?