-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudp-receiver.c
83 lines (68 loc) · 1.74 KB
/
udp-receiver.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Recieve packets from udp-sender, and write nanosecond timestamps and packet
sequence numbers to stdout.
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include "stdint.h"
//################################################################################
unsigned long long
now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return 1000*1000*1000 * ts.tv_sec + ts.tv_nsec;
}
#define MSGBUFSIZE 100000
int
main(int argc, char* argv[])
{
char buf[MSGBUFSIZE];
struct sockaddr_in addr, cli_addr;
int sockfd, listen_port, optval;
unsigned long long sequence, timestamp;
if (argc != 2) {
fprintf(stderr, "usage: %s LISTEN_PORT\n", argv[0]);
exit(1);
}
listen_port = atoi(argv[1]);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
optval = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(optval));
bzero((char *) &addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons((unsigned short)listen_port);
if (bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
perror("bind");
exit(1);
}
while (1) {
socklen_t addrlen = sizeof(cli_addr);
int recv_bytes = recvfrom(sockfd, buf, MSGBUFSIZE, 0, (struct sockaddr*)&cli_addr, &addrlen);
if (recv_bytes < 0) {
perror("recvfrom");
exit(1);
}
timestamp = now_ns();
if (recv_bytes >= sizeof(sequence)) {
bcopy(buf, (char *)&sequence, sizeof(sequence));
printf("%llu %llu\n", timestamp, sequence);
fflush(stdout);
}
}
return 0;
}