linux下用户程序同内核通信详解(netlink机制)

2019-10-10 16:14:31王旭

2. netlink.h

/* 
 * usrlink.h 
 * 
 * Created on: 2014 *  Author: cr 
 */ 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <asm/types.h> 
#include <linux/socket.h> 
#include <linux/netlink.h> 
#ifndef USRLINK_H_ 
#define USRLINK_H_ 
 
#define USER_NETLINK_CMD 25 
#define MAXMSGLEN   1024 
 
typedef enum error_e { 
 NET_ERROR, 
 NET_OK, 
 NET_PARAM, 
 NET_MEM, 
 NET_SOCK, 
} netlink_err; 
 
typedef enum module_e { 
 HELLO_CMD = 1, 
} netlink_module; 
 
typedef enum type_e { 
 HELLO_SET, 
 HELLO_GET, 
} netlink_type; 
 
typedef struct usr_sock_h { 
 int sock; 
 struct sockaddr_nl dest; 
 struct sockaddr_nl src; 
} netlink_sock; 
 
int netlink_sock_init(netlink_sock *netlink_s, int module, int protocol); 
int netlink_sock_deinit(netlink_sock *netlink_s); 
int netlink_send(netlink_sock *netlink_s, int type, char *sbuf, int slen, char *rbuf, int *rlen); 
 
#endif /* USRLINK_H_ */ 

3. main.c

/* 
 * main.c 
 * 
 * Created on: 2014骞?鏈?7鏃? *  Author: cr 
 */ 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include "usrlink.h" 
 
int parse_ret(int ret) 
{ 
 switch(ret) 
 { 
 case NET_OK: 
  return ret; 
 case NET_ERROR: 
  printf("errorn"); 
  goto exit_p; 
 case NET_MEM: 
  printf("Memory errorn"); 
  goto exit_p; 
 case NET_PARAM: 
  printf("Param errorn"); 
  goto exit_p; 
 case NET_SOCK: 
  printf("Socket errorn"); 
  goto exit_p; 
 default:break; 
 } 
exit_p: 
 return NET_ERROR; 
} 
 
void usage(void) 
{ 
 printf("Usage: Netlink -G <param>nt-S <param>n"); 
} 
 
int main(int argc, char **argv) 
{ 
 netlink_sock h_sock; 
 char rbuf[1024]; 
 char sbuf[1024]; 
 int ret, type, slen = 0, rlen = 0; 
 
 ret = netlink_sock_init(&h_sock, HELLO_CMD, USER_NETLINK_CMD); 
 if(NET_OK != parse_ret(ret)) 
  goto exit_p; 
 
 bzero(&rbuf, sizeof(rbuf)); 
 bzero(&sbuf, sizeof(sbuf)); 
 if(argc < 3) 
 { 
  usage(); 
  goto exit_p; 
 } 
 if(!strncmp("-G", argv[1], 2)) 
  type = HELLO_GET; 
 else if(!strncmp("-S", argv[1], 2)) 
  type = HELLO_SET; 
 
 strcpy(sbuf, argv[2]); 
 slen = strlen(sbuf); 
 ret = netlink_send(&h_sock, type, sbuf, slen, rbuf, &rlen); 
 if(NET_OK != parse_ret(ret)) 
  goto exit_p; 
 
 if(rlen > 0) 
 { 
  rbuf[rlen] = ''; 
  printf("K rep [len = %d]:%sn", rlen, rbuf); 
 } 
 printf("K[len = %d]: %sn", rlen, rbuf); 
 
exit_p: 
 netlink_sock_deinit(&h_sock); 
 return 0; 
} 

总结

以上就是本文关于linux下用户程序同内核通信详解(netlink机制)的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!