如何以编程方式确定将使用哪个源IP地址到达给定的目标IP地址 [英] How to programatically determine which source IP address will be used to reach a given destination IP address

查看:149
本文介绍了如何以编程方式确定将使用哪个源IP地址到达给定的目标IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌入式应用程序,该应用程序将部署在众多第三方系统上,并且我需要它检查与之通信的每个目标地址是否都使用确定性和静态的源IP地址(我知道它将与哪个目标IP地址通信)至)。

I have an embedded application which will be deployed on numerous third party systems and I need it to check that a deterministic and static source IP address is used for each destination address it communicates with (I know which destination IP addresses it will talk to).

第三方必须保持自由,以自己认为合适的方式实施IP路由(同时遵守这些约束),我只需要检查它是否具有确定性和静态性,

The third party must remain free to implement their IP routing how they feel fit (while complying to these constraints), I just need to check that it is deterministic and static and ideally know what it will be.

它是一个C应用程序,尽管可以在Solaris或Linux上运行。

Its a C application though can run on either Solaris or Linux.

我想这可能需要询问路由表?

I imagine that this could require interrogation of Routing tables?

有什么想法吗?

推荐答案

对我来说(在Windows和Linux计算机上),其工作方式是创建一个套接字 SOCK_DGRAM ,然后在此套接字上调用 connect()到所需的目标地址。如果调用成功,则调用 getsockname()以获取通过该套接字发送数据时将使用哪个本地地址。

The way it works for me (both in Windows and Linux machines) is to create a socket SOCK_DGRAM, and call connect() on this socket to the desired destination address. If the call is successful, then call getsockname() to get which local address would be used if you sent data over this socket.

Kinda像这样(基于工作代码,为简便起见删除了错误检查):

Kinda like this (based on working code, error checking removed for brevity):

const char * destination_address = "8.8.8.8";
sockaddr_storage Addr = { 0 };
unsigned long addr = inet_addr( destination_address );
( ( struct sockaddr_in * ) &Addr)->sin_addr.s_addr = addr;
( ( struct sockaddr_in * ) &Addr)->sin_family = AF_INET;
( ( struct sockaddr_in * ) &Addr)->sin_port = htons( 9 ); //9 is discard port

int Handle = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
socklen_t AddrLen = sizeof(Addr);
connect( Handle, (sockaddr*)&Addr, AddrLen);
getsockname(Handle, (sockaddr*)&Addr, &AddrLen);
char* source_address = inet_ntoa(((struct sockaddr_in *)&Addr)->sin_addr);

printf( "source address: %s\n", source_address );

其中 destination_address 是您想要的地址到达, source_address 应该包含IP堆栈选择到达的地址。

Where destination_address is the address you want to reach, source_address should contain the address that the IP stack chose to reach it.

这篇关于如何以编程方式确定将使用哪个源IP地址到达给定的目标IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆