c++ – Bind boost::asio socket to new port
You should technically close and reopen. Your original code
socket s(ioc, udp::endpoint(udp::v4(), port));
is roughly equivalent to
socket s(ioc);
s.open(udp::v4());
s.bind(udp::endpoint(udp::v4(), port));
So, what you could do is
s.close();
s.open(udp::v4());
s.bind(udp::endpoint(udp::v4(), other_port));
As far as I remember some calls are documented to automatically close/re-open the socket if needed, but I’d rather be explicit.
Note
I’d venture that it is rarely a useful idea to re-use an IO object when the native handle isn’t. See this very similar question: How to get boost::asio::acceptor to accept connections again after closing it?
In the end it’s probably easier to “just” replace the entire s instance than to manage its state manually.
Read more here: Source link
