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

标签 android linux networking android-ndk gateway

我在 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/

相关文章:

regex - UNIX 如何删除只有逗号和空格的行

linux - 什么是 linux irq 域,为什么需要它们?

java - Java Server Socket连续运行会出现什么问题

linux - 使用HDMI端口作为网络协议(protocol)接口(interface)?

Android Vector Drawable <text> 不支持,<tspan> 不支持

android - "loading"使用 cordova (phonegap) 时自动附加 div

android - 无法创建选项卡内容,因为在 Android Eclipse 中找不到 ID 为 -1 的 View XML 错误?

php - 将 IOS 表情符号转换为网页或安卓表情符号代码

Linux (zip) : how to find all files that are not readable?

Python Scapy wrpcap - 如何将数据包附加到 pcap 文件?