获取关于C中插座可用的字节由'的recv'与'MSG_PEEK'的数量++ [英] Get the number of bytes available in socket by 'recv' with 'MSG_PEEK' in C++

查看:166
本文介绍了获取关于C中插座可用的字节由'的recv'与'MSG_PEEK'的数量++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++具有以下功能接收来自插座字节,它可以检查可用MSG_PEEK标志的字节数。随着MSG_PEEK标志'的recv'的返回值是字节的插座可用的数量。

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

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

我需要在插座可用的字节数,而无需创建缓冲(即不为'缓冲'分配内存),这可能吗?怎么样?

推荐答案

您正在寻找的是的ioctl(FD,FIONREAD,&安培; bytes_available),和windows下 ioctlsocket(插座,FIONREAD,&安培; bytes_available)。

You're looking for is ioctl(fd,FIONREAD,&bytes_available) , and under 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);

如果你不想坐在那里等待数据,你应该看看选择的epoll 以确定数据准备好要读取或不是,如果你想确保你从来没有在一个recv的阻止套接字 O_NONBLOCK 标志是非常方便的。

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

这篇关于获取关于C中插座可用的字节由'的recv'与'MSG_PEEK'的数量++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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