【问题标题】:How to connect my device to wifi with libnl?如何使用 libnl 将我的设备连接到 wifi?
【发布时间】:2019-09-02 19:31:26
【问题描述】:

我正在创建一个 C 库来管理我的嵌入式设备的大量外围设备。 S.O. used,是一个用 yocto 编译的 linux dristro。我正在尝试使用 netlink(使用 libnl 命令)创建一些功能以将我的设备连接到 wifi(众所周知)路由器。在这个社区的帮助下,我开发了一个能够扫描link here 区域内的路由器的功能。你们中有些人知道如何使用 libnl 命令将我的设备连接到路由器 wifi?

我开发了以下代码,尝试连接到名为“Validator_Test”的 AP(没有用于身份验证的密码)。软件没有返回错误,但我的设备仍然与 ap 断开连接。

static int iw_conn() {

    struct nl_msg *msg = nlmsg_alloc();

    int if_index = if_nametoindex("wlan0"); // Use this wireless interface for scanning.

    // Open socket to kernel.
    struct nl_sock *socket = nl_socket_alloc();  // Allocate new netlink socket in memory.
    genl_connect(socket);  // Create file descriptor and bind socket.
    int driver_id = genl_ctrl_resolve(socket, "nl80211");  // Find the nl80211 driver ID.

    genlmsg_put(msg, 0, 0, driver_id, 0, (NLM_F_REQUEST | NLM_F_ACK), NL80211_CMD_CONNECT, 0); 

    nla_put_u32(msg, NL80211_ATTR_IFINDEX, if_index);  // Add message attribute, which interface to use.

    nla_put(msg, NL80211_ATTR_SSID, strlen("Validator_Test"), "Validator_Test"); 

    nla_put(msg, NL80211_ATTR_MAC, strlen("00:1e:42:21:e4:e9"), "00:1e:42:21:e4:e9");  

    int ret = nl_send_auto_complete(socket, msg);  // Send the message.
    printf("NL80211_CMD_CONNECT sent %d bytes to the kernel.\n", ret);
    ret = nl_recvmsgs_default(socket);  // Retrieve the kernel's answer. callback_dump() prints SSIDs to stdout.
    nlmsg_free(msg);

    if (ret < 0) {
        printf("ERROR: nl_recvmsgs_default() returned %d (%s).\n", ret, nl_geterror(-ret));
        return ret;
    }

    nla_put_failure:
    return -ENOSPC;
}

【问题讨论】:

  • 我认为这个问题太宽泛了,请提供一个讨论的方法。

标签: c linux wifi netlink iwconfig


【解决方案1】:

看起来和这个类似: How to use libnl and netlink socket for connect devices to AP programatically?

-- 感谢您的代码。

根据你的代码,我在这里修改并做了测试;有用。源码在:https://github.com/neojou/nl80211/blob/master/test_connect/src/test_connect_nl80211.c

对此的一些建议:

确保测试环境正确

在测试代码之前,也许你可以尝试使用 iw 来做测试。 iw 是开源工具,它也使用 netlink。您可以键入“sudo iw wlan0 connect Validator_Test”,然后使用 iwconfig 先查看它是否已连接。 (假设你说的AP没有安全设置)

你的源代码和我的有两个不同

(1) 不需要设置NL80211_ATTR_MAC

(2) ret = nl_recvmsgs_default(socket);

不确定你的ap_conn()的返回值有没有判断,但是在nl_recvmsgs_default()返回0的时候,ap_conn()中返回0似乎更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多