在我第一次编写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);
}
}
答案 0 :(得分:1)
recvfrom
会将数据报截断为缓冲区的大小。
recvfrom
返回缓冲区大小这一事实意味着您的缓冲区大小不够大,请尝试将其增加到65535字节 - 理论UDP数据报的最大大小。