c++ - 从路由中获取源地址

标签 c++ linux boost routes

this users example通过使用 command line utility 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 
$ 

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

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

在我的例子中,我对 C 感兴趣 - 我正在尝试弄清楚如何才能在我的 中获得相同的信息。程序。具体

  • 给定地址A,求地址C
  • 不想使用system或任何会以某种方式运行 shell 命令的东西
  • 使用是允许的,并且是首选

有什么建议吗?谢谢

最佳答案

你去吧:

#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';
}

关于c++ - 从路由中获取源地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38732194/

相关文章:

visual-studio - 使用 Visual Studio 测试适配器 boost 单元测试 - 设置工作目录

boost::smart_ptr 的 C++ 非侵入式 boost 序列化

c++ - 如何使用 lambda 创建 ReadHandler

c++ - 找不到 PDB Visual Studio 2010

c++ - "Ambiguous call to overloaded function"在 MSVC 编译器中带有枚举类

c++ - 'for' 循环内的后增量和预增量产生相同的输出

c - 文件系统树遍历

java - 面试问题 - 在排序数组 X 中搜索索引 i 使得 X[i] = i

linux - 添加尾部斜杠 mod_rewrite

MYSQL 与脚本的输出不同