Can't set keep_alive to socket in asio

Solution 1:

@Vasile, your problem, as @dewaffed told you, is that you are setting the options before the socket has been opened.

I don't know what you are trying to do but I can see that you creating a new socket, which is not open, and setting the properties, that's the problem. The correct way is:

  1. Create the Socket
  2. Accept the new connection, with the previous socket you've created.
  3. Once the acceptor has ended to accept a new connection, the socket has a valid File Descriptor, which is required to set the option over the socket.

Check these links:

https://en.wikipedia.org/wiki/Berkeley_sockets

Modifying boost::asio::socket::set_option, which talks about your exception.

https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio/tutorial/tutdaytime2.html