Reputation: 13
I haven’t yet successfully found a way to change the port of a boost asio udp socket at run time, after the initialization. Is this possible or would I have to close the socket and re-open with a completely new socket? Thanks in advance.
For some background, I initialized the socket using socket(io_service, udp::endpoint(udp::v4, port)) and then use an async_receive_from() function to receive the data.
Upvotes: 1
Views: 583
Reputation: 393759
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.
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.
Upvotes: 0