示例:

#include <linux/xfrm.h> #include <linux/socket.h> #include <linux/netlink.h> #include <linux/netlink.h> #include <net/xfrm.h>

void create_xfrm_sa(struct xfrm_usersa_info *usa) { struct nlmsghdr *nlh; struct sockaddr_nl nladdr; struct nlattr *attrs[XFRMA_MAX + 1]; struct sk_buff *skb; int err, len;

/* Allocate a new netlink message */
len = nlmsg_total_size(sizeof(struct xfrm_usersa_info));
nlh = nlmsg_alloc(len, GFP_KERNEL);
if (!nlh)
    return;

/* Set up the netlink message headers */
nlh->nlmsg_len = len;
nlh->nlmsg_type = XFRM_MSG_NEWSA;
nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
nlh->nlmsg_pid = current->pid;
nlh->nlmsg_seq = 0;

/* Set up the netlink destination address */
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;

/* Add the xfrm_usersa_info attributes to the netlink message */
err = nla_put(nlh, XFRMA_SA, sizeof(struct xfrm_usersa_info), usa);
if (err < 0)
    goto errout;

/* Send the netlink message */
skb = nlmsg_new(sizeof(struct xfrm_usersa_info), GFP_KERNEL);
if (!skb)
    goto errout;

nlmsg_dump(skb, nlh);
nlmsg_seq(skb, 0);
nlmsg_pid(skb, current->pid);
memcpy(nlmsg_data(nlh), usa, sizeof(struct xfrm_usersa_info));

err = netlink_unicast(sock_net(sk), skb, nladdr.nl_pid, MSG_DONTWAIT);
if (err < 0)
    goto errout;

return;

errout: if (nlh) nlmsg_cancel(nlh); if (skb) nlmsg_free(skb); }

上述代码实现了通过socket接口的XFRM_MSG_NEWSA类型新增一个xfrm_usersa_info的功能。具体实现过程为:先分配一个新的netlink消息,设置好消息头和目的地址,然后将xfrm_usersa_info结构体加入到消息中,最后发送消息。如果出现错误,则释放已经分配的资源

544内核应用层通过socket接口的XFRM_MSG_NEWSA类型新增一个xfrm_usersa_info的C代码

原文地址: https://www.cveoy.top/t/topic/gsib 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录