更新时间:2023-02-12 18:12:23
对我来说(在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.