4以上内核的Python网络链路多播通信

2024-04-26 05:11:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在4(4.1)以上的内核上复制上一个SO post的示例:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netlink.h>
#include <net/netlink.h>
#include <net/net_namespace.h>

/* Protocol family, consistent in both kernel prog and user prog. */
#define MYPROTO NETLINK_USERSOCK
/* Multicast group, consistent in both kernel prog and user prog. */
#define MYGRP 31

static struct sock *nl_sk = NULL;

static void send_to_user(void)
{
    struct sk_buff *skb;
    struct nlmsghdr *nlh;
    char *msg = "Hello from kernel";
    int msg_size = strlen(msg) + 1;
    int res;

    pr_info("Creating skb.\n");
    skb = nlmsg_new(NLMSG_ALIGN(msg_size + 1), GFP_KERNEL);
    if (!skb) {
        pr_err("Allocation failure.\n");
        return;
    }

    nlh = nlmsg_put(skb, 0, 1, NLMSG_DONE, msg_size + 1, 0);
    strcpy(nlmsg_data(nlh), msg);

    pr_info("Sending skb.\n");
    res = nlmsg_multicast(nl_sk, skb, 0, MYGRP, GFP_KERNEL);
    if (res < 0)
        pr_info("nlmsg_multicast() error: %d\n", res);
    else
        pr_info("Success.\n");
}

static int __init hello_init(void)
{
    pr_info("Inserting hello module.\n");

    nl_sk = netlink_kernel_create(&init_net, MYPROTO, NULL);
    if (!nl_sk) {
        pr_err("Error creating socket.\n");
        return -10;
    }

    send_to_user();

    netlink_kernel_release(nl_sk);
    return 0;
}

static void __exit hello_exit(void)
{
    pr_info("Exiting hello module.\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");

但是,编译工作正常,但是当我插入模块时,它返回:

^{pr2}$

我甚至不知道,在哪里可以查找错误代码来了解-3在这个上下文中的含义(我搜索了here,但是找不到任何有用的关于错误代码的东西)。在

为了确定起见,我还发布了userland代码(Python):

由于评论而编辑:(但仍不工作)

#!/usr/bin/env python

import socket
import os
import time

sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, socket.NETLINK_USERSOCK)

# 270 is SOL_NETLINK and 1 is NETLINK_ADD_MEMBERSHIP
sock.setsockopt(270, 1, 31)

while 1:
  try:
    print sock.recvfrom(1024)
  except socket.error, e:
    print 'Exception'

Tags: infohelloincludeinitnlmsgprsocket
1条回答
网友
1楼 · 发布于 2024-04-26 05:11:07

你忘了绑插座。:-)

我对Python不是很流利,所以只将其作为起点(介于socket和{}之间):

sock.bind((0, 0))

它给我印了一堆垃圾,我能看到其中的一些

^{pr2}$

顺便说一句:当nlmsg_multicast()抛出ESRCH时,通常(或者可能总是)因为没有客户在监听。在

首先打开客户机,然后尝试从内核发送消息。在

否则,您总是可以忽略对您的用例有意义的错误代码。在

相关问题 更多 >