关于4.x内核的内核态socket编程问题(sock_create_kern)

关于4.x内核的内核态socket编程问题(sock_create_kern)

tags : linux socket


linux内核态socket编程如何实现:(以tcp服务端举例)

1、sock_create_kern()
2、kernel_setsockopt()这一步为可去掉的,但是如果想socket进行配置,则需要此步骤,例如配置成非阻塞模式:

struct timeval tv;

tv.tv_sec = 0;
tv.tv_usec = 1000 * RECV_WATI_TIME_MS;
kernel_setsockopt(sock_srv, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));

3、kernel_bind()
4、kernel_listen()
5、kernel_accept()
6、kernel_sendmsg()/kernel_recvmsg()
7、sock_release()

其他的也都类似,这里不记录了。

关于不同版本的linux对于sock_create_kern函数的定义

linux2.x的版本

int sock_create_kern(int family, int type, int protocol, struct socket **res)
{
    return __sock_create(family, type, protocol, res, 1);
}

linux3.x的版本:

int sock_create_kern(int family, int type, int protocol, struct socket **res)
{
    return __sock_create(&init_net, family, type, protocol, res, 1);
}

linux4.x的版本

int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res)
{
    return __sock_create(net, family, type, protocol, res, 1);
}

所以,这里在4.x版本里面创建socket的话,最简单的方式是这样调用:

sock_create_kern(&init_net, family, type, protocol, res);

还有一个create socket的函数不要用!!!

int sock_create(int family, int type, int protocol, struct socket **res)
{
    return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0);
}

如果用这个函数创建socket,可以成功的bind、listen、accept,但是一到sendmesg、recvmesg就会出现permission denied。

先在这里插个眼,今后有空的时候再来研究下struct net *net相关的内容,把原因补上。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值