C++ boost 1.72 reconnect on tcp::socket throwing an exception with WSAEADDRINUSE on linux, but works on Windows

Issue

Hi my code works properly on windows but on linux the reconnect feature doesn’t work,it throws an exception with WSAEADDRINUSE value.

pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001));

First time it works on both Windows and Linux, but when i close the socket and try to connect again, i am getting an exception as described above only on linux OS.

Here is the close socket code.

boost::system::error_code ec;
pClientSocket->shutdown( boost::asio::socket_base::shutdown_type::shutdown_receive, ec);
pClientSocket->close(eCode);

delete pClientSocket;

pClientSocket= nullptr;

Solution

Try using the reuse option:

boost::asio::socket_base::reuse_address option(true);
socket.set_option(option);

Update:

This usually happens we you try to bind a server socket to an address that is already in use or it has been used recently (and the socket is still waiting to be cleaned up by the OS).

With client sockets this is less common, you will have to force a port -by calling bind()- in the socket in order for this to happen.

Now the code:

pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001)); 
boost::asio::socket_base::reuse_address option(true); 
socket.set_option(option);

Calls this constructor overload. This constructor creates the socket and tries to bind it to the specified address. It fails because you didn’t had the chance to specify the reuse option.

On the other hand, this code:

pClientSocket = new tcp::socket(*pIO_context); 
pClientSocket->open(boost::asio::ip::tcp::v4()); 
pClientSocket->set_option(socket_base::reuse_address(true));

boost::system::error_code ec; 
pClientSocket->bind(tcp::endpoint(make_address(127.0.0.1, 50001), ec); 
if (ec) { }

Calls this constructor overload, which just creates the socket but doesn’t open no connect it. This allows to specify any socket option before bind/connect, etc.

Answered By – JuanR

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published