Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly randomly assign a port to a test HTTP server using boost asio?

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.

like image 729
Ben J Avatar asked Dec 07 '22 06:12

Ben J


2 Answers

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

like image 150
Reuven Abliyev Avatar answered Jan 07 '23 03:01

Reuven Abliyev


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.

like image 27
Dave Taflin Avatar answered Jan 07 '23 03:01

Dave Taflin