I am new to Boost.asio and C++. I am trying to create a simple program which listens on a certain port for data and displays that data on the terminal. When the simple server (my C++, boost.asio code) is running and I go to the terminal on my computer (Mac) and use the nc command it connects without a problem. The problem is when I try to connect to the program using nc from an Ubuntu VM on VirtualBox, the program does not receive any data. Since the TCP acceptor is 0.0.0.0 I don’t understand why my terminal on host will connect to the program’s listening port but the VM won’t connect to program’s listening port. Any help would be greatly appreciated.
Echo “hello” | nc on Terminal displays hello in program command line but running this command on VM doesn’t display in program command line
For extra info running above command from the VM to a listening port on host Terminal works just fine, so the VM can connect to my computer
#include <iostream>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
using boost::asio::ip::tcp;
int main() {
try {
boost::asio::io_context io_context;
tcp::endpoint endpoint(boost::asio::ip::address_v4::any(), 0);
tcp::acceptor acceptor(io_context, endpoint);
tcp::endpoint local_endpoint = acceptor.local_endpoint();
unsigned short port = local_endpoint.port();
std::cout << "Listening for connections on port " << port << "..." << std::endl;
while (true) {
tcp::socket socket(io_context);
boost::system::error_code ec;
acceptor.accept(socket, ec);
if (ec) {
std::cerr << "Connection rejected: " << ec.message() << std::endl;
continue;
}
std::cout << "Connection accepted from " << socket.remote_endpoint() << std::endl;
std::string data;
while (true) {
char buf[1024];
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof) {
break;
} else if (error) {
std::cerr << "Error during read: " << error.message() << std::endl;
break;
}
data.append(buf, len);
std::cout.write(buf, len);
std::cout.flush();
}
std::cout << "nConnection closed." << std::endl;
boost::system::error_code ignored_ec;
socket.shutdown(tcp::socket::shutdown_both, ignored_ec);
socket.close(ignored_ec);
break;
}
acceptor.close();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}