确定准备好进行 recv() 处理的字节数

发布于 2024-09-27 19:12:47 字数 128 浏览 1 评论 0原文

我可以使用 select() 来确定对 recv() 的调用是否会阻塞,但是一旦我确定有字节要读取,有没有办法在实际调用 recv() 之前查询当前有多少字节可用?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌生 2024-10-04 19:12:47

如果您的操作系统提供了它(大多数操作系统都提供了),则可以使用 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;
}

: call 应该适用于套接字和其他一些 fd,但不是所有 fd。我相信它可以在您可能使用的几乎任何免费的类 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.

简美 2024-10-04 19:12:47

不,协议需要确定这一点。例如:

  • 如果您使用固定大小的消息,那么您知道您需要读取 X 字节。
  • 您可以读取指示要读取 X 字节的消息标头。
  • 您可以阅读直到找到终止字符/序列。

No, a protocol needs to determine that. For example:

  • If you use fixed-size messages then you know you need to read X bytes.
  • You could read a message header that indicates X bytes to read.
  • You could read until a terminal character / sequence is found.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文