gpt4 book ai didi

android - 检索Android手机的默认网关

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:32 24 4
gpt4 key购买 nike

我在 android 中编写 native 应用程序,我需要在我的应用程序上获取设备的默认网关。这是我当前获取默认网关的代码。

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?我在某处读到它不包含在 bionic 中。

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

谢谢

最佳答案

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

另见 this related question .

关于android - 检索Android手机的默认网关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8208074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com