从路由获取源地址

dtm*_*and 1 c++ linux boost routes

这个实施例的用户的路由是通过使用所获得的命令行实用程序的IP。输出示例:

$ ip route get 4.2.2.1
4.2.2.1 via 192.168.0.1 dev eth0  src 192.168.0.121 
    cache 
$ 
Run Code Online (Sandbox Code Playgroud)

让我们以以下方式引用地址:

  • 4.2.2.1作为地址A(目的地)
  • 192.168.0.1作为地址B(网关)
  • 192.168.0.121作为地址C(来源)

就我而言,我感兴趣C-并且我试图弄清楚我如何能够在我的程序中获得相同的信息。特别

  • 给定地址A,找到地址C
  • 不想使用系统或将以某种方式运行shell命令的任何东西
  • 允许使用,并且首选

有什么建议吗?谢谢

mas*_*ash 5

你去了:

#include <iostream>

#include "boost/asio/io_service.hpp"
#include "boost/asio/ip/address.hpp"
#include "boost/asio/ip/udp.hpp"

boost::asio::ip::address source_address(
    const boost::asio::ip::address& ip_address) {
  using boost::asio::ip::udp;
  boost::asio::io_service service;
  udp::socket socket(service);
  udp::endpoint endpoint(ip_address, 0);
  socket.connect(endpoint);
  return socket.local_endpoint().address();
}

// Usage example:
int main() {
  auto destination_address = boost::asio::ip::address::from_string("8.8.8.8");
  std::cout << "Source ip address: "
            << source_address(destination_address).to_string()
            << '\n';
}
Run Code Online (Sandbox Code Playgroud)