The answers to the questions are the following:
- The default gateway is easily found from
/proc/net/route
. It's the route having mask of zero, and destination of zero. All of the hex values are in network byte order, so if IP addresses need to be pretty-printed or compared to addresses in host byte order, ntohl
may be required.
- The easiest way to find the IP address towards the default gateway is to create a UDP socket, not
bind()
it, connect()
it to the default gateway, and use getsockname()
to find the IP address it was automatically bound to.
With these features, my PCP client requires absolutely no manual IP address configuration whatsoever. It automatically detects the default gateway and the IP address towards the default gateway.
For (1), an alternative could be NETLINK sockets, but it's much easier to parse /proc/net/route
. A second alternative could be to fork
and exec
netstat
with a pipe
on its output, and parse its output, but this will make the program dependent on an external binary.
An alternative to (2) could be also to use NETLINK sockets to find the local IP addresses, and then try to deduce which address would be used to connect to the default gateway, but it's much easier to let the Linux kernel do the deduction automatically and read the result using getsockname()
. A second alternative could be to fork
and exec
ip
or ifconfig
with a pipe
on its output, and parse its output and decuce which IP address would be used (the first field of /proc/net/route
gives the interface of the default route, so the interface name is already known), but this will also make the program dependent on an external binary, and ifconfig
may not be installed always, and also this will require doing the deduction process in the user space.