1

On the first run - bind successful, when i restart program - error 10048( address already use)

without calling close and shutdown - restart everything is fine

boost::asio::io_service _ioService;
boost::asio::ip::tcp::socket _socket(_ioService);


boost::system::error_code err;
_socket.open(boost::asio::ip::tcp::v4(), err);
if (err.value())
{
    cout<<err.value()<<endl;
    cout << err.message() << endl;
}

_socket.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1276), err);
cout << err.value() << endl;

if (err.value())
{
    cout << err.value() << endl;
    cout << err.message() << endl;
}

_socket.connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1500), err);
if (err.value())
{
    cout << err.value() << endl;
    cout << err.message() << endl;
}

_socket.shutdown(_socket.shutdown_both);
_socket.close(err);

if (err.value())
{
    cout << err.value() << endl;
    cout << err.message() << endl;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Kopkan
  • 150
  • 11
  • I tried running this code, but I added error reporting to each call. My first error occurs at the connect() call. "Connection refused". This in turn causes an error on the shutdown() call. "Transport endpoint is not connected." The call to close() did not yield any errors. So, maybe your problem occurs with the call to connect. Still, I would expect that to cause your version of the shutdown call to generate an exception, so maybe not. – Jim Vargo Jun 24 '16 at 23:08

1 Answers1

1

The problem is that, the socket may have entered a TIME-WAIT state. See Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

You can set the option to reuse the address: that should prevent such TIME-WAIT See this explanation and a more comprehensive version here.

In Boost.ASIO, you can do it this way:

//Add this

boost::asio::socket_base::reuse_address reuse_address_option(true);
m_socket.set_option(reuse_address_option);

m_socket.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1250), err);

EDIT

After digging through the source code of acceptor there is an example in the source documentation, reproduced here

// @par Example
// Opening a socket acceptor with the SO_REUSEADDR option enabled:
// @code
boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68