-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserver_UDP_LookHowManyInRecvBufferButNotRead_MSG_PEEK.c
60 lines (53 loc) · 1.57 KB
/
server_UDP_LookHowManyInRecvBufferButNotRead_MSG_PEEK.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include "../../tool/AddrTool.h"
int main(int argc, char const *argv[])
{
if (argc != 2) {
printf("usage : %s <port>\n", argv[0]);
exit(1);
}
int fd = -1;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket fd create fail!");
exit(1);
}
struct sockaddr_in svraddr, cliaddr;
bzero(&svraddr, sizeof(svraddr));
svraddr.sin_family = AF_INET;
svraddr.sin_port = htons(atoi(argv[1]));
svraddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr *)&svraddr, sizeof(svraddr)) < 0) {
perror("bind error!");
exit(1);
}
ssize_t nCanReadInRecvBuffer = 0;
ssize_t nread = 0;
char buf[1024];
for (;;) {
if ((nCanReadInRecvBuffer = recvfrom(fd, buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT, NULL, NULL)) < 0) {
if (errno == EAGAIN) {
nCanReadInRecvBuffer = 0;
} else {
perror("recv error!");
exit(1);
}
}
sleep(1);
printf("there are [ %zd ] bytes in recv buffer\n", nCanReadInRecvBuffer);
if (nCanReadInRecvBuffer == 0)
continue;
if ((nread = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL)) < 0) {
perror("recvfrom error!");
exit(1);
}
buf[nread] = 0;
printf("read from udp socket fd %zd bytes, content = %s\n", nread, buf);
}
return 0;
}