libnl的基本使用(根据通用netlink family name获得通用netlink family id)

(1)libnl下载地址http://www.infradead.org/~tgr/libnl/
(2)将下载的代码进行编译后,在.lib/.libs下生成如下的静态库
   libnl-3.a  libnl-genl-3.a  libnl-idiag-3.a  libnl-nf-3.a  libnl-route-3.a  libnl-xfrm-3.a
(3)新建测试文件te.c代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <netlink/genl/genl.h>
#include <netlink/netlink.h>
#include <errno.h>

int main(int argc,char *argv[])
{
   int err;
   struct nl_sock *nlsock;
   int famid;

   nlsock = nl_socket_alloc();
   if(NULL == nlsock)
   {
       printf("socket error\n");
       return -1;
    }

   err = genl_connect(nlsock);
   if(err != 0)
   {
       printf("netlink connect error\n");
       goto out;
    }
    
   //"testnet"为某个family name
   famid = genl_ctrl_resolve(nlsock,"testnet");
   if(famid <= 0)
       printf("Not found fam id by this name[%s]\n","testnet");
   else
       printf("famid= %d\n",famid);
out:
    nl_socket_free(nlsock);
    return 0;
}


(4)编译gcc te.c  -pthread -lm ./libnl-3.a ./libnl-genl-3.a -I./include  -o  te

//创建一个netlink socket
struct nl_sock *nl_socket_alloc(void)

//释放一个netlink socket
void nl_socket_free(struct nl_sock *sk)

//连接一个通用netlink socket
int genl_connect(struct nl_sock *sk) 
 
//根据通用netlink family名获得family id
//通过调用genl_ctrl_probe_by_name向内核发送CTRL_CMD_GETFAMILY命令
int genl_ctrl_resolve(struct nl_sock *sk, const char *name)

猜你喜欢

转载自blog.csdn.net/yldfree/article/details/82593873