netlink测试程序的编写

12 篇文章 0 订阅

有幸看到文章的童鞋,送上一句话。

linux内核的编程遥遥无期,也不知到何时才是头,至少我们知道未来是光明的,而且也为解决的每一个问题感到兴奋无比。


下面是我查找大牛的相关netlink详解和代码,重新写了一遍,也想大家能自己写一遍,熟悉一下流程。

the kernel moduule:

/*
*                    how to program use netlink to communicate
*                    between the kernel space and the user spaece 
*                                                         by:dead_angel
*                                                       date:Apr.19,2013
*/


/*
*                        the kernel space module.             */
#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/module.h>
#include<net/netlink.h>
#include<net/sock.h>

#define NETLINK_TEST 25  /*VALUE>16*/
#define MAXMSGSIZE 1024


int pid = 0;
int flag = 0;
struct sock* sock = NULL;


/* send the message */
void nl_sendmsg(char * msg)
{
  //1)declare a struct sk_buff*
  //2)declare a struct nlmsghdr *
  //3)call alloc_skb() to alloc the struct skb_buff 
  //4)appenxid the struct nlmsg to the tail of the struct skb_buff
  //5)get the nlmsghdt ponit to the field of the struct skb_buff
  //6)init the fiels of the nlmsg
  //7)insrt the meg into the mlmsg
  //8)call the netlink_unicast() to transmit the struct skb_buff
  struct sk_buff * skbuftmp = NULL;
  struct nlmsghdr* nlh = NULL; 
  unsigned int len_msg = 0;
  //len_msg = get_len(msg);
  len_msg=strlen(msg);
  int len = NLMSG_SPACE(MAXMSGSIZE);
  if(!msg&&!sock)
    {
      return ;
    }
  skbuftmp = alloc_skb(len,GFP_KERNEL);
  if(!skbuftmp)
    {
      printk("alloc_skb();failed!\n"); 
      return ;
    }
  nlh = nlmsg_put(skbuftmp,0,0,0,MAXMSGSIZE,0);
  NETLINK_CB(skbuftmp).pid = 0;
  NETLINK_CB(skbuftmp).dst_group = 0;
  msg[len_msg] = '\0';
  
  memcpy(NLMSG_DATA(nlh),msg,len_msg+1);
  printk("the send str = %s \n ", (char*)NLMSG_DATA(nlh));
  netlink_unicast(sock,skbuftmp,pid,MSG_DONTWAIT);
}

/*the callback function */

void  nl_data_ready(struct sk_buff* skbuf)
{
  struct completion cmpl;
  struct nlmsghdr* nlh = NULL;
  struct sk_buff * skbbuftmp = skb_get(skbuf);
  if(skbbuftmp->len>=NLMSG_SPACE(0))
    {
      /* point to the nlmsg */
      nlh = nlmsg_hdr(skbbuftmp);
      char buf[MAXMSGSIZE] = "";
      memcpy(buf,NLMSG_DATA(nlh),MAXMSGSIZE);
      printk("the get msg = %s",buf);
      pid = nlh->nlmsg_pid;
    
      int i = 10;
      while(i--)
          {
             init_completion(&cmpl);
             wait_for_completion_timeout(&cmpl,3*HZ);
             nl_sendmsg("this is a kernel program which use the netlink to communicate with the user space !\n");
             printk("send ok !\n");
          }
      flag = 1;
      kfree_skb(skbbuftmp);
    }
}


/* the module init */
static int netlink_init(void)
{
  printk("the netlink test!\n");
  sock = netlink_kernel_create(&init_net,NETLINK_TEST,1,nl_data_ready,NULL,THIS_MODULE);
  return 0;
}

/* the module exit */
static void netlink_exit(void)
{
  if(sock!=NULL)
    {
     sock_release(sock->sk_socket);
    }
  printk("quit the netlink test!\n");
}


module_init(netlink_init);
module_exit(netlink_exit);

MODULE_AUTHOR("dead_angel");
MODULE_LICENSE("GPL");

the user program:

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

#define NETLINK_TEST 25
#define MAX_PAYLOAD  1024


void main()
{
   /* create the socket */
   unsigned int sock = socket(AF_NETLINK,SOCK_RAW,NETLINK_TEST);
   if(sock==-1)
     {
       printf("create the socket frailed!\n");
       return ;
     }

   /* init the src addr */
   struct sockaddr_nl  src,dst;
   memset(&src,0,sizeof(struct sockaddr_nl));
   src.nl_family = AF_NETLINK;
   src.nl_pid = getpid();
   src.nl_groups = 0;
   if(bind(sock,(struct sockaddr*)&src,sizeof(struct sockaddr_nl))<0)
     {
        printf("bind failed!\n");
        close(sock);
        return ;
     }

   /* init the dst addr */
   memset(&dst,0,sizeof(struct sockaddr_nl));
   dst.nl_family = AF_NETLINK;
   dst.nl_pid = 0;
   dst.nl_groups = 0;   

   /* create the netlink packet */
   struct nlmsghdr* nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
   if(nlh == NULL)
     {
        printf("malloc failed!\n");
        close(sock);
        return;
     }
   nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
   nlh->nlmsg_pid = getpid(); 
   nlh->nlmsg_flags = 0;
   strcpy(NLMSG_DATA(nlh),"hello! the kernel module!\n");
  
   struct iovec iov;
   memset(&iov,0,sizeof(struct iovec));
   iov.iov_base = (void*)nlh;
   iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
  
   struct msghdr msgh;
   memset(&msgh,0,sizeof(struct msghdr));
   msgh.msg_name = (void*)&dst;
   msgh.msg_namelen = sizeof(struct sockaddr_nl);
   msgh.msg_iov = &iov;
   msgh.msg_iovlen = 1;

   printf("send msg to kernel!\n");
   if(sendmsg(sock,&msgh,0)==-1)
     {
       printf("send failed!\n");
       close(sock);
       return;
     } 
   
   memset(nlh,0,NLMSG_SPACE(MAX_PAYLOAD));
   printf("begin to recv msg!\n");
   while(1)
        { 
          if(recvmsg(sock,&msgh,0)!=-1)
            {
              printf("msg = %s\n",(char*)NLMSG_DATA(nlh));
            }
        }    

   close(sock);
   return ;    
}

the Makefile:

obj-m := netlink_kernel.o
KERNELBUILD := /lib/modules/`uname -r`/build 
default: 
	@echo "BUILE Kmod" 
	@make -C $(KERNELBUILD) M=$(shell pwd) modules 
	gcc -o netlink_user netlink_user.c 
clean: 
	@echo " CLEAN kmod" 
	@rm -rf *.o 
	@rm -rf .depend .*.cmd *.ko *.mod.c .tmp_versions *.symvers .*.d


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、imp2源码 整个源码包含三个文件:imp2_k.c, imp2_u.c和imp2.h. 其中imp2_k.c为内核模块的源代码,imp2_u.c为应用程序,即测试代码,imp2.h为两个源文件都需要引用的头文件。其整体的功能是:注册一种新的netlink协议,并注册一个新的NF hook函数。当有ping包发往当前主机或者经过当前主机转发时,内核向用户发送ping包的源IP和目的IP。各个文件的简单分析见下文。 1. imp2.h 该文件主要是定义了一种新的Netlink协议类型NL_IMP2(31)。新的协议类型的选值不能和当前内核中已经定义的netlink协议类型重复。定义了基于该协议类型的消息类型,内核根据接收到消息的不同类型,进行不同的处理:IMP2_U_PID和IMP2_CLOSE分别为请求和关闭。IMP2_K_MSG代表内核空间发送的消息。 该头文件的源码如下: 2. imp2_k.c 该程序为内核模块程序。其完成的功能如下: (1)创建一种新的Netlink协议NL_IMP2,并注册该协议的回调函数kernel_receive。但用户空间通过建立且协议类型为NL_IMP2的socket套接字并调用sendto,sendmsg函数发送数据时,传送到内核空间的数据由kernel_receive进行处理。该函数主要是记录用户进程的ID,用于随后发送数据的时候指定目的。 (2)在Netfilter的hook点NF_IP_PRE_ROUTING注册hook函数get_icmp,对经过该hook点的ping包进行处理。get_icmp首先判断是否是ping包,如果不是,直接Accept。如果是,则记录该包的源IP和目的IP,然后调用send_to_user,将记录的信息发送给kernel_recieve函数中记录的用户进程ID。 该文件的源码如下: 3. imp2_u.c 该程序为用户空间的测试程序。该程序包括以下功能: (1)生成NL_IMP2协议的socket.然后通过调用sendto发送IMP2_U_PID类型的请求信息给内核。然后等待接受内核发回的信息。记住:仅当有ping包经过内核的NF时,内核才会向用户进程发送信息。 (2)当用户进程通过Ctrl+C来结束该程序时,调用信号处理函数sig_int,向内核发送IMP2_CLOSE的消息,结束socket。 该文件的源码如下: 二、编译和测试 1. 整个源文件编译的Makefile如下: all: gcc -O2 -DMODULE -D__KERNEL__ -W -Wstrict-prototypes -Wmissing-prototypes -isystem /lib/modules/`uname -r`/build/include -c -o imp2_k.o imp2_k.c gcc imp2_u.c -o imp2_u install: insmod imp2_k.o uninstall: rmmod imp2_k clean: rm -f imp2_k.o imp2_u 2. 加载内核模块,并执行测试程序。 #make install #./imp2_u 当没有ping包时,终端一直处于等待输出状态。通过另一台主机(192.168.1.100)向当前主机(192.168.1.101)发送ping包,则终端已经有输出: #./imp2_u [root@localhost imp2]# ./imp2_u src: 192.168.1.100, dest: 192.168.1.101 src: 192.168.1.100, dest: 192.168.1.101 src: 192.168.1.100, dest: 192.168.1.101 src: 192.168.1.100, dest: 192.168.1.101
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值