确定准备好recv()的字节数(Determing the number of bytes ready to be recv()'d)

编程入门 行业动态 更新时间:2024-10-22 13:52:48
确定准备好recv()的字节数(Determing the number of bytes ready to be recv()'d)

我可以使用select()来确定对recv()的调用是否会阻塞,但是一旦我确定它们是要读取的字节,它是一种在我实际调用recv之前查询当前可用的字节数的方法( )?

I can use select() to determine if a call to recv() would block, but once I've determined that their are bytes to be read, is their a way to query how many bytes are currently available before I actually call recv()?

最满意答案

如果你的操作系统提供它(大多数都提供),你可以使用ioctl(..,FIONREAD,..):

int get_n_readable_bytes(int fd) { int n = -1; if (ioctl(fd, FIONREAD, &n) < 0) { perror("ioctl failed"); return -1; } return n; }

Windows提供了一个类似的ioctlsocket(..,FIONREAD,..),它需要一个指向unsigned long的指针:

unsigned long get_n_readable_bytes(SOCKET sock) { unsigned long n = -1; if (ioctlsocket(sock, FIONREAD, &n) < 0) { /* look in WSAGetLastError() for the error code */ return 0; } return n; }

ioctl调用应该适用于套接字和其他一些fds,但不适用于所有fds。 我相信它可以在几乎任何你可能使用的免费类Unix操作系统上使用TCP套接字。 它的语义与UDP套接字略有不同:对于它们,它告诉你下一个数据报中的字节数。

Windows上的ioctlsocket调用(显然)只适用于套接字。

If your OS provides it (and most do), you can use ioctl(..,FIONREAD,..):

int get_n_readable_bytes(int fd) { int n = -1; if (ioctl(fd, FIONREAD, &n) < 0) { perror("ioctl failed"); return -1; } return n; }

Windows provides an analogous ioctlsocket(..,FIONREAD,..), which expects a pointer to unsigned long:

unsigned long get_n_readable_bytes(SOCKET sock) { unsigned long n = -1; if (ioctlsocket(sock, FIONREAD, &n) < 0) { /* look in WSAGetLastError() for the error code */ return 0; } return n; }

The ioctl call should work on sockets and some other fds, though not on all fds. I believe that it works fine with TCP sockets on nearly any free unix-like OS you are likely to use. Its semantics are a little different for UDP sockets: for them, it tells you the number of bytes in the next datagram.

The ioctlsocket call on Windows will (obviously) only work on sockets.

更多推荐

本文发布于:2023-07-04 17:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1027015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   Determing   recv   ready   bytes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!