如何检查可用的数据量在C和Linux套接字 [英] How to check amount of data available for a socket in C and Linux

查看:166
本文介绍了如何检查可用的数据量在C和Linux套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接收数据的连续流的服务器。相对于从套接字读取多次,我想读取整个数据套接字接收一个系统调用缓冲到阅读()

I have a server that receives a continuous stream of data. As opposed to reading multiple times from a socket, I would like to read the entire data in socket receive buffer with one system call to read().

当然,我可以通过一个大的缓冲区和阅读()将尝试与所有可用的数据来填充它。但是,这会浪费大量的内存,因为大多数的时代malloc分配的缓冲区会大于实际数据可用插槽。有没有一种方法来查询一个插座上的可用数据?

Of course I can pass a large buffer and read() will try to fill it with all available data. But this would waste a lot of memory as most of the times the malloc'ed buffer would be bigger than actual data available on socket. Is there a way to query the available data on a socket?

推荐答案

是:

#include <sys/ioctl.h>

...

int count;
ioctl(fd, FIONREAD, &count);

这篇关于如何检查可用的数据量在C和Linux套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆