从路由获取源地址

Obtain source address from route

本文关键字:源地址 获取 路由      更新时间:2023-10-16

在这个用户示例中,通过在linux中使用命令行实用程序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-很感兴趣,我正试图弄清楚如何在我的c++程序中获得相同的信息。特别是

  • 给定地址A,查找地址C
  • 不想使用系统或任何会以某种方式运行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';
}

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

更正代码:

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