0

I am coding a native application in android and I need to get the default gateway of a device on my application. Here is my current code to get the default gateway.

static int get_default_gateway(char *def_gateway, int buf_size)
{
    FILE* pipe;
    char buffer[128];
    char result[2049];

    char cmd[] = "netstat -r | grep ^default | awk '{print $2}'";

    pipe = popen(cmd, "r");
    if (!pipe) return 1;

    memset(result, 0, sizeof(result));

    while(!feof(pipe)) {
        memset(buffer, 0, sizeof(buffer));
        if(fgets(buffer, 128, pipe) != NULL)
        {
              strcat(result, buffer);
        }       
    }
    pclose(pipe);

    memset(def_gateway, 0, buf_size);
    strncpy (def_gateway, result, buf_size );

    return 0;
}

It works on my LG p500 but on some devices it doesn't return anything.

My question is: Does popen() works on android? I read somewhere that it is not included in bionic.

And is there any other method to get the default gateway? I need it to be written in C and not java.

Thank you

skaffman
  • 398,947
  • 96
  • 818
  • 769
kuchi
  • 840
  • 11
  • 19

1 Answers1

1

Yea, probably popen() should work on any Android. But unfortunately grep and awk - not. Take a look at /proc/net/route - line where Destination equals to 00000000 is your default gateway. Also perhaps you can use NETLINK_ROUTE socket, though I never used it and can't say more.

See also this related question.

Community
  • 1
  • 1
praetorian droid
  • 2,989
  • 1
  • 17
  • 19