Boost::asio linux tcp client - how to set network interface?

13 Views Asked by At

I want to use boost::asio for simple TCP client on linux, but I need to set up a network interface through which the client will communicate. Is this possible in boost::asio?

Here is a piece of code that I am trying to set up an interface. In classic sockets, it was not a problem to set the interface before connect, but in boost::asio the socket is not functional before connect. Setting the interface only after connect is probably stupid...

using boost::asio::ip::tcp;

boost::asio::io_context io_context;
tcp::socket socket(io_context);
tcp::resolver resolver(io_context);
std::string interface("eth0");

tcp::resolver::results_type endpoints = 
    resolver.resolve(address, std::to_string(port));

boost::asio::connect(socket, endpoints);

// Set-up network interface
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface.c_str());
if (setsockopt(socket.native_handle(), SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
    throw std::runtime_error(std::string("It is not possible to set interface ")
                        + interface + ": " + strerror(errno));
}

0

There are 0 best solutions below