内容: 当使用udp socket的recvfrom函数的时候,如果指定缓冲区大小不够会怎么样
问题:
当recvfrom接收udp socket的数据的时候,如果你用来接收的缓冲区太小,那么会出现让你
惊讶的情况
服务端实例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main()
{
struct sockaddr_in srvAddr;
bzero(&srvAddr,sizeof(srvAddr));
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
srvAddr.sin_port = htons(8888);
int srvAddrLen = sizeof(srvAddr);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
bind(fd, (struct sockaddr *)&srvAddr, sizeof(srvAddr));
while(1)
{
char buff[6] = {0};
int ret = recvfrom(fd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&srvAddr, (socklen_t*)&srvAddrLen);
printf("msg from client : %s,the length is %d\n", buff, ret);
}
close(fd);
return 0;
}
客户端实例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main()
{
struct sockaddr_in srvAddr;
bzero(&srvAddr, sizeof(srvAddr));
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
srvAddr.sin_port = htons(8888);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
while(1)
{
printf("press any key to send data\n");
getchar();
char buff[128] = {0};
snprintf(buff, sizeof(buff), "hello world");
printf("send size is %d\n", strlen(buff));
sendto(fd, buff, strlen(buff), 0, (struct sockaddr *)&srvAddr, sizeof(srvAddr));
}
close(fd);
return 0;
}
服务端运行结果:
luzejia@ubuntu:~$ gcc server.c -o server
luzejia@ubuntu:~$ ./server
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
msg from client : hello,the length is 5
客户端运行结果:
luzejia@ubuntu:~$ ./client
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
send size is 11
press any key to send data
结果解析:
1、udp的数据报传输方式是数据报,不是数据流,不存在粘包,拆包问题,但是发几次就需要几次来收
2、如果收包长度不过,多的会被丢弃,而不会在下次recvfrom的时候取到
3、在使用udp socket编程的时候,如果buffer太小,出现接收不完整的错误也不会返回错误给你
4、若出现没有办法一次性读走所有内容,就只读缓冲区能存的,但是读到用户缓冲区,内核的缓冲
区中的内容是一直存在的,因此运行结果会出现根本没读后面的world单词,后续继续读也不会
读到剩余的world。