Search code examples
c++boosttcpboost-asiovpn

boost::asio::connect reports success on wrong subnet


Using Boost v1.74:

int main()
{
    auto ctx = boost::asio::io_context{};
    auto socket = boost::asio::ip::tcp::socket{ctx};
    auto ep = boost::asio::ip::tcp::endpoint{
                     boost::asio::ip::make_address_v4("192.168.0.52"),
                     80};
    boost::asio::connect(socket, std::array{std::move(ep)});

    std::cout << "Success!" << std::endl;
}

The IP address of my machine on my local network is 192.168.0.31/24, and so trying to connect to a non-existent address in the same subnet with the above code gives:

10:24:55: Starting /home/cmannett85/workspace/build-scratch-Desktop-Debug/scratch ...
terminate called after throwing an instance of 'boost::wrapexcept<boost::system::system_error>'
  what():  connect: No route to host
10:24:59: The program has unexpectedly finished.

This is all expected. If I change the bottom octet of the subnet in the address (e.g. 192.168.1.52), then the app just waits for a few minutes - presumably because it sent messages to any routers to see if they own the requested subnet. There aren't any routers on my network, so it eventually times out:

10:27:39: Starting /home/cmannett85/workspace/build-scratch-Desktop-Debug/scratch ...
terminate called after throwing an instance of 'boost::wrapexcept<boost::system::system_error>'
  what():  connect: Connection timed out
10:29:49: The program has unexpectedly finished.

Again, as expected. If I change the next octet (e.g. 192.167.0.52) instead, I would expect this to behave exactly the same as it is an equally unknown subnet as the previous. But it suceeds!

10:31:22: Starting /home/cmannett85/workspace/build-scratch-Desktop-Debug/scratch ...
Success!

This address is definitely not on my network:

$ ping 192.167.0.52
PING 192.167.0.52 (192.167.0.52) 56(84) bytes of data.
^C
--- 192.167.0.52 ping statistics ---
17 packets transmitted, 0 received, 100% packet loss, time 16368ms

So why is the code reporting that it is connected? And why is changing the second octet different to the third?


Solution

  • Any IP address of the form 192.168.xx.xx is a non-internet-routable network. This means no internet routers will route it. So the only way packets get routed off your subnet is if you configure a route on your own router or host. 192.167.xx.xx is an internet routable network, Presumable there is a host out there on the internet that uses the address you specified. So if you can connect your host to the internet, some internet router will get your packet to the address specified.