Home > Software design >  Get the interface to be used by socket according to IP on Linux, with C/C
Get the interface to be used by socket according to IP on Linux, with C/C

Time:12-26

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?

CodePudding user response:

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.

  • Related