Netlink 内核实现分析 4
阅读原文时间:2023年07月12日阅读:6

netlink 库函数:

http://www.infradead.org/~tgr/libnl/doc/core.html#core_netlink_fundamentals

#define NETLINK_TEST (31)

static
int s_send_ack_to_test(struct lua_nl_ack *ack)
{
struct sk_buff *nl_skb;
struct nlmsghdr *nlh;

int ret;  
int len = sizeof(\*ack);

nl\_skb = nlmsg\_new(len, GFP\_ATOMIC);  
if (!nl\_skb) {  
    pr\_err("netlink: nlmsg\_new fail\\n");  
    return -1;  
}

nlh = nlmsg\_put(nl\_skb, 0, 0, NETLINK\_WNS, len, 0);  
if(nlh == NULL) {  
    pr\_err("netlink: nlmsg\_put fail\\n");  
    nlmsg\_free(nl\_skb);  
    return -1;  
}

memcpy(nlmsg\_data(nlh), (void \*)ack, len);  
ret = netlink\_unicast(nlsk, nl\_skb, NETLINK\_WNS\_LUA, MSG\_DONTWAIT);

return ret;  

}

static
void test_input_cb(struct sk_buff *skb)
{
struct nlmsghdr *nlh = NULL;
struct lua_nl_req *req = NULL;
struct lua_nl_ack ack;

nlh = (struct nlmsghdr \*)skb->data;

if (NLMSG\_OK(nlh, skb->len) && skb->len >= NLMSG\_HDRLEN + sizeof(struct lua\_nl\_req)) {  
    req = (struct lua\_nl\_req \*)NLMSG\_DATA(nlh);

    (void)s\_get\_ip\_mac(req, &ack);

    if (s\_send\_ack\_to\_test(&ack) < 0) {  
        pr\_err("netlink: s\_send\_ack\_to\_lua error\\n");  
    }

    //TODO: netlink消息失败的情况需要再仔细考虑下,可能导致阻塞

}  
else {  
    pr\_err("netlink: parameters error\\n");  
}

return ;  

}

static struct netlink_kernel_cfg cfg = {
.input = test_input_cb,
};

static
int s_init_netlink()
{
nlsk = netlink_kernel_create(&init_net, NETLINK_TEST, THIS_MODULE, &cfg);
if (!nlsk) {
pr_err("netlink: init fail\n");
return -1;
}

return 0;  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章