用户空间与内核空间通信一(多播)

/******************************************************************************
 *
 * Description:
 *   Netlink multicast user space testing module.
 *   User space: client.
 *   Kernel space: server multicast.
 *
 * User space
 *****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/socket.h>

#define MAX_PAYLOAD 1024
#define NETLINK_TEST 21
#define GRP_ID 1 
/******************************************************************************
 *
 * Description:
 *   Main function.
 *
 * Paramter:
 *   Null.
 *
 * Return:
 *   int.
 *
 *****************************************************************************/

int main(void)
{
	struct sockaddr_nl src_addr, dest_addr;
	struct nlmsghdr *nlh = NULL;
	struct iovec iov;
	int sock_fd = 0;
	struct msghdr msg;
	
	/* Initialize data field */
	memset(&src_addr, 0, sizeof(src_addr));
	memset(&dest_addr, 0, sizeof(dest_addr));
	memset(&iov, 0, sizeof(iov));
	memset(&msg, 0, sizeof(msg));
	
	/* Create netlink socket use NETLINK_SELINUX(7) */
	if ((sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST)) < 0) {
		perror("socket");
		return -1;
	}

	/* Fill in src_addr */
	src_addr.nl_family = AF_NETLINK;
	src_addr.nl_pid = getpid();
	/* Focus */
	src_addr.nl_groups = GRP_ID;

	if (bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr)) < 0) {
		perror("bind");
		return -1;
	}

	/* Fill in dest_addr */
	dest_addr.nl_pid = 0;
	dest_addr.nl_family = AF_NETLINK;
	/* Focus */
	dest_addr.nl_groups = GRP_ID;

	/* Initialize buffer */
	if((nlh = (struct nlmsghdr*)malloc(NLMSG_SPACE(MAX_PAYLOAD))) == NULL) {
		perror("malloc");
		return -1;
	}
	memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
	iov.iov_base = (void *)nlh;
	iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
	msg.msg_name = (void *)&dest_addr;
	msg.msg_namelen = sizeof(dest_addr);
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;
	
	/* Recv message from kernel */
	recvmsg(sock_fd, &msg, 0);

	printf("%d: Recv message from kernel: %s\n", getpid(), NLMSG_DATA(nlh));
	close(sock_fd);

	return 0;
}

你可能感兴趣的:(usr,netlink,Multicast)