0

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?

SdtElectronics
  • 566
  • 4
  • 8
  • Well, since Linux is open source, presumably you can look at the source code for `route`, see what it does, and do exactly the same thing yourself? – Sam Varshavchik Dec 24 '21 at 15:29
  • What is in the routing table determines which interface will be used. The route with the longest match wins, and ties use the tied route with the lowest metric. The default route (`0.0.0.0/0`) matches everything, but it is the shortest match (`0` length), so it is used only if there is no other match. – Ron Maupin Dec 24 '21 at 15:36
  • I don't think there's a built-in API to do this, so you have to process the routing table yourself. – Barmar Dec 24 '21 at 15:45

1 Answers1

1

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.