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

/******************************************************************************
 *
 * Description: 
 *   Netlink function test module, userspace test routine.
 *   This routine is a client and test unicast.
 *
 *User space
 *
 *
 *****************************************************************************/

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

/* Private Netlink protocol */
#define NETLINK_TEST 31
/* Maximum payload size */
#define MAX_PAYLOAD 1024

/******************************************************************************
 *
 *  Description:
 *    Main function
 *
 *  Parameter:
 *    VOID
 *
 *  Return:
 *     0: Successed
 *    -1: Failed
 *
 *****************************************************************************/
int main(void)
{
	int nl_sock = 0;
	struct msghdr msg;
	struct sockaddr_nl src_addr, dest_addr;
	struct iovec iov;
	struct nlmsghdr *nlh = NULL;

	memset(&msg, 0, sizeof(msg));
	memset(&src_addr, 0, sizeof(src_addr));
	memset(&dest_addr, 0, sizeof(dest_addr));
	
	if ((nl_sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST)) < 0) {
		perror("socket");
		return -1;
	}
	
	/* Assign src_addr */
	src_addr.nl_family = AF_NETLINK;
	src_addr.nl_pid = getpid(); /* self pid */
	src_addr.nl_groups = 0; /* Unicast */
	
	if (bind(nl_sock, (struct sockaddr*)&src_addr, sizeof(src_addr)) < 0) {
		perror("bind");
		return -1;
	}
	
	/* Assign dest_addr */
	dest_addr.nl_family = AF_NETLINK;
	dest_addr.nl_pid = 0; /* From Linux Kernel */
	dest_addr.nl_groups = 0; /* Unicast */

	if ((nlh = (struct nlmsghdr*)malloc(NLMSG_SPACE(MAX_PAYLOAD))) 
			== NULL) {
		perror("malloc");
		return -1;
	}
	
	/* Fill the netlink message header */
	nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
	nlh->nlmsg_pid = getpid(); /* Self pid */
	nlh->nlmsg_flags = 0;

	/* Fill the netlink message payload */
	strcpy(NLMSG_DATA(nlh), "Netlink message from User space.\n");

	iov.iov_base = (void*)nlh;
	iov.iov_len = nlh->nlmsg_len;
	msg.msg_name = (void*)&dest_addr;
	msg.msg_namelen = sizeof(dest_addr);
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;

	/* Send message to kernel */
	sendmsg(nl_sock, &msg, 0);
	printf("Send message to kernel.\n");

	/* Read message from kernel */
	memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
	recvmsg(nl_sock, &msg, 0);
	printf("Received message from kernel: %s\n", NLMSG_DATA(nlh));
	
	close(nl_sock);

	return 0;
}

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