Thursday, May 31, 2012

GetBestInterface for Linux or How to get source IP by target IP

Lets assume that you need to know which source IP address will be used to send information to known target IP address.
In Windows you can use GetBestInterface function. But Linux doesn't have something the same (or I don't know about it :)
The possible solution is to create socket connection to the target IP and call getsockname function. It returns sockaddr struct that you can use to get source IP address for this connection.

I suppose that this approach works for Windows also but I preffer to use GetBestInterface for this OS.

Here you can find source code sample  :)