检索Android手机的默认网关

发布于 2024-12-17 15:49:07 字数 830 浏览 2 评论 0原文

我正在 Android 中编写一个本机应用程序,我需要在我的应用程序上获取设备的默认网关。这是我当前获取默认网关的代码。

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;
}

它适用于我的 LG p500,但在某些设备上它不会返回任何内容。

我的问题是:popen()可以在android上运行吗?我在某处读到它不包含在仿生中。

还有其他方法可以获取默认网关吗?我需要用C而不是java编写。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人间☆小暴躁 2024-12-24 15:49:07

是的,也许 popen() 应该适用于任何 Android。但不幸的是 grep 和 awk - 不是。查看 /proc/net/route - Destination 等于 00000000 的行是您的默认网关。也许你也可以使用 NETLINK_ROUTE 套接字,尽管我从未使用过它并且不能说更多。

另请参阅此相关问题

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文