hostapd --- 使用 wpa_ctrl 监听 STA的连接断开情况

以下是一个完整的 C 程序示例,演示如何通过 wpa_ctrl 和 wpa_ctrl_attach 监听 STA 的连接和断开事件,并提取 MAC 地址:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <wpa_ctrl.h>

#define CTRL_INTERFACE "/var/run/hostapd/wlan0"

int main() {
    struct wpa_ctrl *ctrl;
    int ret;

    // 打开 hostapd 控制接口
    ctrl = wpa_ctrl_open(CTRL_INTERFACE);
    if (ctrl == NULL) {
        fprintf(stderr, "Failed to open control interface to %s\n", CTRL_INTERFACE);
        return 1;
    }

    // 附加到 hostapd 事件监听
    ret = wpa_ctrl_attach(ctrl);
    if (ret != 0) {
        fprintf(stderr, "Failed to attach to hostapd events\n");
        wpa_ctrl_close(ctrl);
        return 1;
    }

    printf("Monitoring STA connections...\n");

    // 监听事件
    while (1) {
        char buf[1024];
        ret = wpa_ctrl_recv(ctrl, buf, sizeof(buf));
        if (ret < 0) {
            fprintf(stderr, "Error receiving data from hostapd\n");
            break;
        }

        buf[ret] = '\0'; // 确保字符串终止

        // 检查事件类型并提取 MAC 地址
        if (strstr(buf, "AP-STA-CONNECTED")) {
            // 示例输出: AP-STA-CONNECTED <MAC地址>
            char *mac = strchr(buf, ' ');
            if (mac != NULL) {
                mac++; // 跳过空格
                printf("STA connected: %s\n", mac);
            }
        } else if (strstr(buf, "AP-STA-DISCONNECTED")) {
            // 示例输出: AP-STA-DISCONNECTED <MAC地址>
            char *mac = strchr(buf, ' ');
            if (mac != NULL) {
                mac++; // 跳过空格
                printf("STA disconnected: %s\n", mac);
            }
        }
    }

    // 关闭控制接口
    wpa_ctrl_detach(ctrl);
    wpa_ctrl_close(ctrl);
    return 0;
}

 

posted @ 2025-06-18 21:33  流水灯  阅读(166)  评论(0)    收藏  举报