iw是一个基于nl80211接口的无线配置工具,用于替代原先基于wext接口的iwconfig。iw源码可以在网址 https://www.kernel.org/pub/software/network/iw/ 获取,或者使用git命令从http://git.kernel.org/?p=linux/kernel/git/jberg/iw.git. 中下载。
1、简单的nl80211程序
iw的源码主体在iw.c文件里,其他文件都是对iw相关的命令选项的实现。
在iw-4.9版本中,iw.c源代码有586行,并不是很多,如果去掉代码中的参数解析部分和命令选项匹配部分,就可以得到iw的最核心的代码,如下面的代码所示。
/**
* 该程序使用nl80211命令从内核中读取wlan0接口信息,
* 然后在回调函数中解析信息,打印出wlan0的接口类型。
*/
#include "netlink/netlink.h"
#include "netlink/genl/genl.h"
#include "netlink/genl/ctrl.h"
#include <net/if.h>
//从iw复制过来
#include "nl80211.h"
static int expected_id;
static int nl_callback(struct nl_msg* msg, void* arg)
{
struct nlmsghdr* ret_hdr = nlmsg_hdr(msg);
struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
if (ret_hdr->nlmsg_type != expected_id)
{
// what is this??
return NL_STOP;
}
struct genlmsghdr *gnlh = (struct genlmsghdr*) nlmsg_data(ret_hdr);
nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0</