【问题标题】:Obtain source address from route从路由中获取源地址
【发布时间】:2016-08-02 23:46:17
【问题描述】:

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 命令的东西
  • 允许使用,并且是首选

有什么建议吗?谢谢

【问题讨论】:

  • 你需要什么A? C 应该是 eth0 的地址。或者您将被路由到哪个接口对您很重要?
  • @mash 是的,这很重要——我的机器有多个接口,所以我想知道使用了哪一个。

标签: linux c++ boost c++ linux boost routes


【解决方案1】:

你去吧:

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

【讨论】:

  • 效果很好。出于好奇,为什么是 UDP 而不是 TCP?
  • 因为在这种情况下您不需要 TCP 提供的功能。
【解决方案2】:

mash 的答案几乎是正确的,但在 iOS 上失败了。 udp::endpoint endpoint(ip_address, 0); 行需要有一个非零端口,否则您将收到错误“无法分配请求的地址”,因为 0 不是有效的端口号。我认为端口是什么并不重要(只要它是一个有效的非零端口号),所以我建议使用标准 UDP STUN 端口 3478。

更正的代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-07
    • 2014-11-22
    • 1970-01-01
    • 2014-09-20
    • 2015-11-13
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多