I am using boost asio to create a test server to test an http client. This will run on the same machine as the client. Now what I want to do is create a server with a randomly assigned port. I have looked at this thread here: Using boost::asio is there a portable way to find out free port number but I'm frankly still a little baffled.
My code looks something like this:
boost::asio::io_service service;
tcp::acceptor acceptor(service);
unsigned short port(0);
tcp::endpoint endPoint(tcp::endpoint(tcp::v4(), port);
acceptor.open(endPoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endPoint);
port = endPoint.port();
std::cout<<port<<std::endl; // prints 0
My thoughts were that by creating an endpoint with 'port 0' and then trying to bind to that port, it should cause an available port to be randomly assigned but this doesn't seem to be the case. Any idea what I'm doing wrong?
Cheers.
boost::asio::io_service service;
boost::asio::ip::tcp::acceptor acceptor(service);
unsigned short port(0);
boost::asio::ip::tcp::endpoint endPoint(tcp::endpoint(tcp::v4(), port);
acceptor.open(endPoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endPoint);
m_acceptor.listen();
boost::asio::ip::tcp::endpoint le = acceptor.local_endpoint(); //THIS LINE SOLVES IT
port = le.port();
// port = endPoint.port(); // This is didn't work for me
Helpful answer Similar question
You can shorten this by using a different constructor for the acceptor:
using boost::asio;
io_service service;
ip::tcp::acceptor acceptor(service, ip::tcp::endpoint(ip::tcp::v4(), 0));
unsigned short port = acceptor.local_endpoint().port();
This constructor calls open(), bind() and listen() on the acceptor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With