• Uncategorized

About c++ : Get-the-interface-to-be-used-by-socket-according-to-IP-on-Linux-with-CC

Question Detail

According to this answer, the interface to be used by a socket will be selected automatically by the system if the destination address is specified when calling connect. What I am looking for is a simple way to know the name of that interface before calling connect with C or C++. I know this can be done with the command route get to $ADDR, but calling external command in program seems kinda dirty. Is there any way to do this in C/C++ other than parsing the route table or calling route?

Question Answer

You can open a netlink socket and query the routes then filter the one you need. Here is an article on Linux Journal that describes this method:

https://www.linuxjournal.com/article/7356

And here is an implementation in C of it:

https://gist.github.com/javiermon/6272065

It just needs a bit of adjustment for your needs.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.