How to get gateway address for IPv6 on Android

From command line execute

# route -n -A inet6

From returned strings select one having “UG” combination in the “flags” column.

Routing table for IPv6 on Android
Routing table for IPv6 on Android.

To do that programmatically open file /proc/net/ipv6_route (see screenshot above). Read it line by line, parse and select entry having flag “gateway” set.
Entries have following format

addr6p                   prerix_len saddr6p                        slen naddr6p                          metric   use      refcnt   iflags      iface
00000000000000000000000000000000 00 00000000000000000000000000000000 00 fe80000000000000ccaccc820e7ef078 00000400 00000000 00000000 00450003     ppp0

Read value of the “iflags” column and check for RTF_GATEWAY. Flags are defined in the “linux/route.h” header as

/* Keep this in sync with /usr/src/linux/include/linux/route.h */
#define RTF_UP          0x0001          /* route usable                 */
#define RTF_GATEWAY     0x0002          /* destination is a gateway     */
#define RTF_HOST        0x0004          /* host entry (net otherwise)   */
#define RTF_REINSTATE   0x0008          /* reinstate route after tmout  */
#define RTF_DYNAMIC     0x0010          /* created dyn. (by redirect)   */
#define RTF_MODIFIED    0x0020          /* modified dyn. (by redirect)  */
#define RTF_MTU         0x0040          /* specific MTU for this route  */
#ifndef RTF_MSS
#define RTF_MSS         RTF_MTU         /* Compatibility :-(            */
#endif
#define RTF_WINDOW      0x0080          /* per route window clamping    */
#define RTF_IRTT        0x0100          /* Initial round trip time      */
#define RTF_REJECT      0x0200          /* Reject route

Code sample

char naddr6p[33];
int num, iflags;
//  Parse rows and get attributes. An example of routing table entry:
//  addr6p                   prerix_len saddr6p                        slen naddr6p                          metric   use      refcnt   iflags      iface
//  00000000000000000000000000000000 00 00000000000000000000000000000000 00 fe80000000000000ccaccc820e7ef078 00000400 00000000 00000000 00450003     ppp0
num = sscanf(t, "%*32s %*02x %*32s %*02x %32s %*08x %*08x %*08x %08x %*s\n", naddr6p, &iflags);

if (num == 2 && (iflags & RTF_GATEWAY)) {
    ...
}

Continue reading