3

当我意识到它已被贬低并且大多数应用程序使用 nl80211 时,我开始使用 iwconfig/ioctl 编写代码来处理 wifi 卡。我开始阅读它的源代码,但没有文档,代码有点复杂。如何使用 nl80211 或 libnl 进行扫描、关闭/打开、设置卡模式等简单操作?这就是我从 iw 开始的:

void set_card_mode(MODE mode, std::string ifname)
{
    int skfd = iw_sockets_open();
    struct iwreq wrq;
    wrq.u.mode = static_cast<unsigned int>(mode);
    power_interface(ifname, false);
    if(iw_set_ext(skfd, ifname.c_str(), SIOCSIWMODE, &wrq) < 0)
        throw std::runtime_error("Can set card mode");
}


MODE get_card_mode(std::string ifname)
{
    int skfd = iw_sockets_open();
    struct iwreq wrq;
    if (iw_get_ext (skfd, ifname.c_str(), SIOCGIWMODE, &wrq) >= 0)
    {
        return static_cast<MODE>(wrq.u.mode);
    }
}

是否有任何等效的 iw_get_ext 来设置/获取 wifi 接口或任何具有“set_mode”或“power_off”等简单功能的 api?

4

1 回答 1

1

我使用以下步骤使用 netlink 进行扫描

  1. 准备并执行NL80211_CMD_TRIGGER_SCAN
  2. 准备并执行 NL80211_CMD_GET_SCAN

    与 NL80211_CMD_GET_SCAN 一起注册了一个回调。在回调中,原始数据被解析为 BSS。IE 被解析为。请参阅 nl80211.h 中带有 NL80211_BSS_MAX、NL80211_ATTR_MAX 的枚举。

在处理下一步之前检查每个 netlink 调用的返回值。

代码片段:

nl_sock* socket = nl_socket_alloc();
genl_connect(socket);
struct nl_msg* msg = nlmsg_alloc();
int driverId = genl_ctrl_resolve(socket, "nl80211"); 
genlmsg_put(msg, 0, 0, driverId, 0, 0, NL80211_CMD_TRIGGER_SCAN, 0);

并获取:

genlmsg_put(msg, 0, 0, driverId, 0, NLM_F_DUMP, NL80211_CMD_GET_SCAN, 0);
nl_socket_modify_cb(socket, NL_CB_VALID, NL_CB_CUSTOM, onScanResult, null);

我的回调开始于:

struct genlmsghdr* msgHeader = (genlmsghdr*)nlmsg_data(nlmsg_hdr(msg));
struct nlattr* attributes[NL80211_ATTR_MAX + 1];
struct nlattr* bss[NL80211_BSS_MAX + 1];
if(nla_parse(attributes, NL80211_ATTR_MAX, genlmsg_attrdata(msgHeader, 0), genlmsg_attrlen(msgHeader, 0), NULL) == 0)
{
    // Read the attributes
    // and check for NL80211_ATTR_BSS != 0
}

我在 NL80211_BSS_INFORMATION_ELEMENTS 中找到了大部分扫描结果。

if (nla_parse_nested(bss, NL80211_BSS_MAX, attributes[NL80211_ATTR_BSS], bss_policy) == 0)
{ /* read the bss attributes */ }

请参阅nl80211.h中的NL80211_BSS_INFORMATION_ELEMENTS

但我没有检查 WEP 隐私。检查 WPA 或 WPA2 很容易,因为有一个 ID 为 48 的额外 IE 元素(Śee IEEE Std 802.11 2012,第 8.4.2 章,从 ieee 端免费下载)

于 2017-04-05T11:01:17.117 回答