【问题标题】:recvfrom() is returning size of buffer instead of number of bytes readrecvfrom() 返回缓冲区的大小而不是读取的字节数
【发布时间】:2024-01-12 03:16:02
【问题描述】:

在准备我第一次编写 UDP 代码时,我正在尝试从 here 复制和轻微修改的一些示例客户端和服务器代码。一切似乎都在工作,除了 recvfrom() 返回的值始终是缓冲区的大小而不是读取的字节数(如果我更改缓冲区大小并重新编译,收到的报告字节数会更改以匹配新的缓冲区大小,尽管在每个测试中发送的字节都是相同的 10 个字节)。

是否有人在此代码中看到任何可以解释问题的错误(为简洁起见,此处删除了一些错误检查)?如果相关,我正在运行 Yosemite 10.10.5 的 Macbook Pro 上的终端窗口中的 bash 中编译和运行:

#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define BUFLEN 1024
#define PORT 9930

int main(void) {
  struct sockaddr_in si_me, si_other;
  int s, i, slen=sizeof(si_other);
  int nrecv;
  char buf[BUFLEN];

  s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  memset((char *) &si_me, 0, sizeof(si_me));
  si_me.sin_family = AF_INET;
  si_me.sin_port = htons(PORT);
  si_me.sin_addr.s_addr = htonl(INADDR_ANY);
  bind(s, &si_me, sizeof(si_me));

  while (1) {
    nrecv = recvfrom(s, buf, BUFLEN, 0, &si_other, &slen);
    printf("Received packet from %s:%d\n%d bytes rec'd\n\n", 
           inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), nrecv);
  }
}

【问题讨论】:

    标签: c udp recvfrom


    【解决方案1】:

    recvfrom 在缓冲区不够大时将数据报截断为缓冲区的大小。

    recvfrom 返回缓冲区大小的事实意味着您的缓冲区大小不够大,请尝试将其增加到 65535 字节 - 最大理论 UDP 数据报大小。

    【讨论】:

    • 啊!我忽略了仔细检查客户端代码 b/c 我的目标实际上只是拥有一个简单的工作服务器来处理来自我正在使用的 android 设备的数据。我使用的客户端示例发送其整个缓冲区,而不仅仅是我错误假设的短消息字符串。这个错误的假设以及我只测试了等于或小于客户端缓冲区大小的服务器缓冲区的事实导致我得出了关于问题所在的错误结论......通常情况下,问题就在我的耳朵之间! ;) 感谢您的帮助!
    最近更新 更多