The environment: C code, Linux
What: I would like to open a port on a router using UPNP for SSH protocol. I know how to do it using miniupnpc library. I can send UPNP request and this request consists of: External port to redirect from Internal port to redirect to The internal machine address accepting the SSH traffic.
Problem: In the case the internal machine has several eth interfaces how do I find the right one?
For example: Say I have:
eth0, address 10.10.10.1 [WAN connection]
eth1, address 20.20.20.1 [No WAN connection]
The eth0 is the interface connected to the router and has WAN access. The eth1 is the interface connected to the internal network doesn't have access to WAN.
When the UPNP request sent it should contain:
External port: 2222
Internal port: 22
Local machine address: 10.10.10.1 [eth0]
The question:
How from C code do I detect which interface accesses WAN? I should not run an external script, C code only. External library usage is OK.
I guess you have to detect which interface has assigned default gateway (zeroes only) by reading content of /proc/net/route or same could be done using netlink interface.
You may want to use socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE) with request of type RTM_GETROUTE. Nice and complete example could be found at for example: oleg's blog. Code may be somehow reduced using libnl. Some details may also be found on linuxfoundation's web.