C语言 在 C++ 中通过 'recv' 和 'MSG_PEEK' 获取套接字中可用的字节数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12984816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:09:51  来源:igfitidea点击:

Get the number of bytes available in socket by 'recv' with 'MSG_PEEK' in C++

csocketsbufferrecvpeek

提问by jondinham

C++ has the following function to receive bytes from socket, it can check for number of bytes available with the MSG_PEEKflag. With MSG_PEEK, the returned value of 'recv' is the number of bytes available in socket:

C++ 有以下函数从套接字接收字节,它可以检查可用的字节数与MSG_PEEK标志。使用MSG_PEEK,'recv' 的返回值是套接字中可用的字节数:

#include <sys/socket.h>
ssize_t recv(int socket, void *buffer, size_t length, int flags); 

I need to get the number of bytes available in the socket without creating buffer(without allocating memory for buffer). Is it possible and how?

我需要在不创建的buffer情况下获取套接字中可用的字节数(不为 分配内存buffer)。有可能吗?

回答by hexist

You're looking for is ioctl(fd,FIONREAD,&bytes_available), and under windows ioctlsocket(socket,FIONREAD,&bytes_available).

您正在寻找 is ioctl(fd,FIONREAD,&bytes_available),并且在 windows 下ioctlsocket(socket,FIONREAD,&bytes_available)

Be warned though, the OS doesn't necessarily guarantee how much data it will buffer for you, so if you are waiting for very much data you are going to be better off reading in data as it comes in and storing it in your own buffer until you have everything you need to process something.

但是请注意,操作系统不一定保证它会为您缓冲多少数据,因此如果您正在等待大量数据,您最好在数据进入时读取数据并将其存储在您自己的缓冲区中直到您拥有处理某事所需的一切。

To do this, what is normally done is you simply read chunks at a time, such as

为此,通常所做的只是一次读取块,例如

char buf[4096];
ssize_t bytes_read;
do {
     bytes_read = recv(socket, buf, sizeof(buf), 0);
     if (bytes_read > 0) {
         /* do something with buf, such as append it to a larger buffer or
          * process it */
     }
} while (bytes_read > 0);

And if you don't want to sit there waiting for data, you should look into selector epollto determine when data is ready to be read or not, and the O_NONBLOCKflag for sockets is very handy if you want to ensure you never block on a recv.

如果您不想坐在那里等待数据,您应该查看selectepoll确定何时准备好读取数据,O_NONBLOCK如果您想确保永远不会阻塞 recv,套接字标志非常方便.

回答by Remy Lebeau

On Windows, you can use the ioctlsocket()function with the FIONREADflag to ask the socket how many bytes are available without needing to read/peek the actual bytes themselves. The value returned is the minimum number of bytes recv()can return without blocking. By the time you actually call recv(), more bytes may have arrived.

在 Windows 上,您可以使用ioctlsocket()带有FIONREAD标志的函数来询问套接字有多少可用字节,而无需读取/查看实际字节本身。返回的值是在recv()不阻塞的情况下可以返回的最小字节数。到您实际调用 时recv(),可能已到达更多字节。