You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过NetworkManager获取热点连接设备列表及IP、MAC地址?

使用NetworkManager获取Wi-Fi热点连接设备及信息

一、通过nmcli工具实现

1. 确定Wi-Fi热点的接口

首先列出当前活跃的网络连接,找到Wi-Fi热点(模式为AP)对应的设备名:

nmcli con show --active

输出中找到TYPE为802-11-wireless且MODE为ap的条目,记下其DEVICE列的值(比如wlan0)。

2. 获取连接到热点的设备MAC地址

使用nmcli查看该接口下已连接的设备:

nmcli device wifi show <你的设备名>

在输出的Connected stations部分,会列出所有连接设备的MAC地址及信号强度。

3. 匹配MAC与IP地址

NetworkManager为热点提供DHCP服务,租约信息存储在/var/lib/NetworkManager/dhcp-<设备名>.leases文件中。直接读取该文件即可获取MAC对应的IP地址:

cat /var/lib/NetworkManager/dhcp-<你的设备名>.leases

文件中每条记录包含hardware ethernet(MAC)和fixed-address(IP)字段,一一对应。

二、通过NetworkManager C API(libnm)实现

libnm是NetworkManager官方提供的C语言库,能直接与NetworkManager的DBus服务交互,更适合集成到应用程序中。

1. 获取连接的设备MAC地址

以下代码片段演示如何获取AP模式Wi-Fi设备下的连接设备MAC及信号强度:

#include <nm-client.h>
#include <nm-device-wifi.h>
#include <nm-station-info.h>
#include <glib.h>

int main() {
    GError *err = NULL;
    NMClient *client = nm_client_new(NULL, &err);
    if (!client) {
        g_printerr("Failed to initialize NMClient: %s\n", err->message);
        g_error_free(err);
        return 1;
    }

    // 遍历所有设备,找到AP模式的Wi-Fi设备
    GList *devices = nm_client_get_devices(client);
    for (GList *l = devices; l; l = g_list_next(l)) {
        NMDevice *dev = NM_DEVICE(l->data);
        if (!NM_IS_DEVICE_WIFI(dev)) continue;

        NMDeviceWifi *wifi_dev = NM_DEVICE_WIFI(dev);
        if (nm_device_wifi_get_mode(wifi_dev) != NM_DEVICE_WIFI_MODE_AP) continue;

        // 获取当前连接的所有客户端
        GList *stations = nm_device_wifi_get_stations(wifi_dev);
        for (GList *s = stations; s; s = g_list_next(s)) {
            NMStationInfo *info = NM_STATION_INFO(s->data);
            const char *mac = nm_station_info_get_hw_address(info);
            guint32 signal = nm_station_info_get_strength(info);
            g_print("Client: MAC=%s, Signal=%u%%\n", mac, signal);
        }
        g_list_free_full(stations, g_object_unref);
    }

    g_list_free_full(devices, g_object_unref);
    g_object_unref(client);
    return 0;
}

编译命令:

gcc -o nm_ap_clients nm_ap_clients.c `pkg-config --cflags --libs libnm`

2. 获取设备IP地址

要获取MAC对应的IP,可通过解析NetworkManager的DHCP租约文件/var/lib/NetworkManager/dhcp-<设备名>.leases,或通过libnm的NMDhcpConfig接口读取租约信息。解析租约文件的方式更直接,只需读取文件内容,匹配hardware ethernet字段与MAC,提取对应的fixed-address即可。

内容的提问来源于stack exchange,提问作者Kill KRT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:15:39