从路由获取源地址
Obtain source address from route
在这个用户示例中,通过在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';
}
相关文章:
- 总是引用的地址等于源地址
- 如何根据指针地址获取指针内容
- 从对象及其成员的地址获取指向成员的指针
- 如何从地址获取字符串?
- 如何确定 cudaErrorIllegalAddress 是由于目标地址还是源地址
- 从内存地址获取值
- 阅读UDP广播的源地址
- PIN从指令地址获取程序集操作码
- 使用数组的地址获取过期指针
- Solaris 10 -- 从 recvmsg() 的 UDP 组播数据包中获取 IP 源地址
- 从调用堆栈地址获取函数参数
- 从IP地址获取完整的计算机名称,例如 abc.xyz.xvvx.net
- 如何通过地址获取元组中元素的索引
- 从成员的地址获取成员的索引
- 从IPv4地址获取网络接口名称
- Windows下如何设置UDP源地址
- 套接字,Unix域UDP c++ recvfrom无法填充源地址
- 如何通过符号在内存中的地址获取有关符号的更多信息
- 正在WinDbg中按地址获取类型
- 从路由获取源地址