aboutsummaryrefslogtreecommitdiffstats
path: root/network_cmds/frame_delay/frame_delay.c
blob: 37a58b7644db32fc4fce5da89c4b9ccd385b134f (plain) (blame)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
 * Copyright (c) 2009-2015 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

/*
 * Usage for frame_delay
 *
 * Server
 *	./frame_delay -m server -t <tcp/udp> -p <port> -n <num_frames> -f <frame_size>
 *
 * Client
 *	./frame_delay -m client -t <tcp/udp> -i <srv_ipv4_add> -p <srv_port> -n <num_frames> -f <frame_size> -d <delay_ms>  -k <traffic_class>
 */

/*
 * TODO list :
 *				1. UDP fragmentation and reassembly
 */

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

/* Server Static variable */
static int so, srv_so;
static int srv_port = 0;
static struct sockaddr_in laddr, dst_addr;
/* Client Static variable */
static struct sockaddr_in srv_addr;
static uint32_t tc = 0;
/* Usage */
void ErrorUsage(void);
/* str2svc */
uint32_t str2svc(const char *str);
/* Show Stastics */
void ShowStastics(int64_t *DiffsBuf, int num_frames);
/* Returns difference between two timevals in microseconds */
int64_t time_diff(struct timeval *b, struct timeval *a);
/* tcp server */
void tcpServer(int frame_size, int num_frames, char *buf, int64_t *DiffsBuf);
/* udp server */
void udpServer(int frame_size, int num_frames, char *buf, int64_t *DiffsBuf);
/* tcp server */
void tcpClient(int num_frames, int frame_size,
			   const char *buf, struct timespec sleep_time);
/* udp server */
void udpClient(int num_frames, int frame_size,
			   const char *buf, struct timespec sleep_time);

/* Main function */
int
main(int argc, char *argv[])
{
	int num_frames = 0, frame_size = 0, delay_ms = 0, rc = 0;
	char *buf = NULL, ch, *type = NULL, *mode = NULL, *ip_addr = NULL;
	int64_t *DiffsBuf;
	struct timespec sleep_time;

	while ((ch = getopt(argc, argv, "m:p:f:n:t:d:i:k:")) != -1) {
		switch (ch) {
			case 'm': {
				mode = optarg;
				break;
			}
			case 'p': {
				srv_port = atoi(optarg);
				break;
			}
			case 'f' : {
				frame_size = atoi(optarg);
				break;
			}
			case 'n' : {
				num_frames = atoi(optarg);
				break;
			}
			case 'i': {
				ip_addr = optarg;
				bzero(&srv_addr, sizeof(srv_addr));
				rc = inet_aton(optarg, &srv_addr.sin_addr);
				if (rc == 0) {
					perror("inet_ntoa failed");
					exit(1);
				}
			}
			case 'd': {
				delay_ms = atoi(optarg);
				break;
			}
			case 't' : {
				type = optarg;
				break;
			}
			case 'k': {
				tc = str2svc(optarg);
				break;
			}
			default: {
				printf("Invalid option: %c\n", ch);
				ErrorUsage();
			}
		}
	}
	/* General check for both server and client */
	if (srv_port <= 0 || frame_size <= 0 || num_frames <= 0 || !mode || !type) {
		ErrorUsage();
	}
	if ( strcmp(type, "tcp") != 0 && strcmp(type, "udp") != 0 ) {
		ErrorUsage();
	}
	/* Allocate memory for buf */
	buf = calloc(1, frame_size);
	if (buf == NULL) {
		printf("malloc failed\n");
		exit(1);
	}
	if ( strcmp(mode, "server") == 0 ) {
		/* Server */
		printf("<LOG>   :   Start %s server on port %d with expected frame size of %d\n",
			   type, srv_port, frame_size);
		DiffsBuf = (int64_t *)calloc(num_frames, sizeof(int64_t));
		if (DiffsBuf == NULL) {
			printf("malloc failed\n");
			exit(1);
		}
		if( strcmp(type, "tcp") == 0) {
			/* tcpServer */
			tcpServer(frame_size, num_frames, buf, DiffsBuf);
		} else {
			/* updServer */
			udpServer(frame_size, num_frames, buf, DiffsBuf);
		}
	}
	else if ( strcmp(mode, "client") == 0 ){
		if ( !ip_addr || (tc > 0 && (tc < SO_TC_BK_SYS || tc > SO_TC_CTL)) ){
			ErrorUsage();
		 }
		/* Client */
		printf("<LOG>   :   Start sending %d %s frames to %s:%d with a frame size of %d\n",
			   num_frames, type, ip_addr, srv_port, frame_size);
		/* Resolving sleep time bug : delay_ms should just be calculated once */
		bzero(&sleep_time, sizeof(sleep_time));
		while (delay_ms >= 1000) {
			sleep_time.tv_sec++;
			delay_ms -= 1000;
		}
		sleep_time.tv_nsec = delay_ms * 1000 * 1000;
		if( strcmp(type, "tcp") == 0) {
			/* Call TCP client */
			tcpClient(num_frames, frame_size, buf, sleep_time);
		} else {
			/* Call UDP client */
			udpClient(num_frames, frame_size, buf, sleep_time);
		}
	} else {
		ErrorUsage();
	}
}

/* Error usage */
void
ErrorUsage(void) {
	printf("Correct Usage");
	printf("Server : frame_delay -m server -t <tcp/udp> -p <port> -n <num_frames> -f <frame_size>\n");
	printf("Client : frame_delay -m client -t <tcp/udp> -i <srv_ipv4_add> -p <srv_port> -n <num_frames> -f <frame_size> -d <delay_ms>  -k <traffic_class>\n");
	exit(1);
}

/* str2svc */
uint32_t
str2svc(const char *str)
{
	uint32_t svc;
	char *endptr;

	if (str == NULL || *str == '\0')
		svc = UINT32_MAX;
	else if (strcasecmp(str, "BK_SYS") == 0)
		return SO_TC_BK_SYS;
	else if (strcasecmp(str, "BK") == 0)
		return SO_TC_BK;
	else if (strcasecmp(str, "BE") == 0)
		return SO_TC_BE;
	else if (strcasecmp(str, "RD") == 0)
		return SO_TC_RD;
	else if (strcasecmp(str, "OAM") == 0)
		return SO_TC_OAM;
	else if (strcasecmp(str, "AV") == 0)
		return SO_TC_AV;
	else if (strcasecmp(str, "RV") == 0)
		return SO_TC_RV;
	else if (strcasecmp(str, "VI") == 0)
		return SO_TC_VI;
	else if (strcasecmp(str, "VO") == 0)
		return SO_TC_VO;
	else if (strcasecmp(str, "CTL") == 0)
		return SO_TC_CTL;
	else {
		svc = (uint32_t)strtoul(str, &endptr, 0);
		if (*endptr != '\0')
			svc = UINT32_MAX;
	}
	return (svc);
}

/* Show Stastics */
void
ShowStastics(int64_t *DiffsBuf, int num_frames) {
	int i = 0;
	int64_t sum = 0, mean = 0;

	/* Mean */
	while(i < num_frames)
		sum += DiffsBuf[i++];
	mean = sum / num_frames;
	printf("<LOG>   :   Mean: %.2f usecs\n", sum / (double)num_frames);
	/* Popular Standard Deviation */
	i = 0;
	sum = 0;
	while(i < num_frames) {
		sum += (DiffsBuf[i]-mean)*(DiffsBuf[i]-mean);
		i++;
	}
	printf("<LOG>   :   Popular Standard Deviation: %.2f usecs\n",
		   sqrt(sum/(double)num_frames));
}

/* Returns difference between two timevals in microseconds */
int64_t
time_diff(struct timeval *b, struct timeval *a)
{
	int64_t usecs;
	usecs = (a->tv_sec - b->tv_sec) * 1000 * 1000;
	usecs += (int64_t)(a->tv_usec - b->tv_usec);
	return(usecs);
}

/* Server */

/* tcp server */
void
tcpServer(int frame_size, int num_frames, char *buf, int64_t *DiffsBuf) {
	int rc = 0, i = 0, ignore_count = 0;
	uint32_t dst_len = 0;
	struct timeval before, after;
	ssize_t bytes;
	int64_t usecs;
	/* New change from Padama */
	uint64_t prev_frame_ts = 0, prev_recv = 0, frame_ts = 0, cur_recv = 0;
	uint64_t min_variation = 0, max_variation = 0, avg_variation = 0;

	printf("<LOG>   :   TCP Server\n");
	so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (so == -1) {
		perror("failed to create socket");
		exit(1);
	}
	bzero(&laddr, sizeof(laddr));
	laddr.sin_family = AF_INET;
	laddr.sin_port = htons(srv_port);
	rc = bind(so, (const struct sockaddr *)&laddr, sizeof(laddr));
	if (rc != 0) {
		perror("failed to bind");
		exit(1);
	}
	rc = listen(so, 10);
	if (rc != 0) {
		perror("failed to listen");
		exit(1);
	}
	srv_so = accept(so, (struct sockaddr *)&dst_addr, &dst_len);
	if (srv_so == -1) {
		perror("failed to accept");
		exit(1);
	}
	while (1) {
		if ( i == num_frames ) {
			printf("<LOG>   :   Completed\n");
			break;
		}
		printf("<LOG>   :   Waiting for receiving\n");
		bzero(&before, sizeof(before));
		bzero(&after, sizeof(after));
		rc = gettimeofday(&before, NULL);
		if (rc == -1) {
			perror("gettimeofday failed");
			exit(1);
		}
		bytes = recv(srv_so, buf, frame_size, MSG_WAITALL);
		if (bytes == -1) {
			perror("recv failed");
			exit(1);
		}
		else if (bytes > 0 && bytes != frame_size) {
			printf("Client exited\n");
			printf("Didn't recv the complete frame, bytes %ld\n",
				   bytes);
			exit(1);
		}
		else if (bytes == 0) {
			break;
		}
		rc = gettimeofday(&after, NULL);
		if (rc == -1) {
			perror("gettimeofday failed");
			exit(1);
		}
		cur_recv = after.tv_sec * 1000 * 1000 + after.tv_usec;
		memcpy((void *)&frame_ts, buf, sizeof(frame_ts));
		if (prev_frame_ts > 0) {
			int64_t d_variation = 0;
			d_variation = (int64_t)((cur_recv - prev_recv) -
									(frame_ts - prev_frame_ts));
			/* printf("Frame %u ts %llu d_variation %lld usecs\n",
			 i, frame_ts, d_variation);*/
			if (d_variation > 0) {
				if (min_variation == 0)
					min_variation = d_variation;
				else
					min_variation = ((min_variation <= d_variation) ?
									 min_variation : d_variation);
				max_variation = ((max_variation >= d_variation) ?
								 max_variation : d_variation);
				avg_variation += d_variation;
			} else {
				ignore_count++;
			}
		}
		prev_recv = cur_recv;
		prev_frame_ts = frame_ts;
		++i;
		/* Compute the time differenc */
		usecs = time_diff(&before, &after);
		DiffsBuf[i] = usecs;
		printf("<LOG>   :   Frame %d received after %lld usecs\n", i, usecs);
	}
	if (i != ignore_count)
		avg_variation = avg_variation / (i - ignore_count);
	else
		avg_variation = 0;

	printf("<LOG>   :   Received frames: %u\n", i);
	printf("<LOG>   :   Ignored frames: %u\n", ignore_count);
	printf("<LOG>   :   Minimum delay variation: %llu usecs\n", min_variation);
	printf("<LOG>   :   Maximum delay variation: %llu usecs\n", max_variation);
	printf("<LOG>   :   Average delay variation: %llu usecs\n", avg_variation);
	ShowStastics(DiffsBuf, num_frames);
}

/* udp server */
void
udpServer(int frame_size, int num_frames, char *buf, int64_t *DiffsBuf) {
	int rc = 0, i = 0, ignore_count = 0;
	uint32_t dst_len = 0;
	ssize_t bytes;
	struct timeval before, after;
	int64_t usecs;
	/* New change from Padama */
	uint64_t prev_frame_ts = 0, prev_recv = 0, frame_ts = 0, cur_recv = 0;
	uint64_t min_variation = 0, max_variation = 0, avg_variation = 0;

	printf("<LOG>   :   UDP Server\n");
	so = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (so == -1) {
		perror("failed to create socket");
		exit(1);
	}
	bzero(&laddr,sizeof(laddr));
	laddr.sin_family = AF_INET;
	laddr.sin_addr.s_addr=htonl(INADDR_ANY);
	laddr.sin_port=htons(srv_port);
	rc = bind(so, (struct sockaddr *)&laddr,sizeof(laddr));
	if (rc != 0) {
		perror("failed to bind");
		exit(1);
	}
	while (1) {
		if ( i == num_frames ) {
			printf("<LOG>   :   Completed\n");
			break;
		}
		printf("<LOG>   :   Waiting for receiving\n");
		bzero(&before, sizeof(before));
		bzero(&after, sizeof(after));
		rc = gettimeofday(&before, NULL);
		if (rc == -1) {
			perror("gettimeofday failed");
			exit(1);
		}
		bytes = recvfrom(so, buf, frame_size, 0, (struct sockaddr *)&dst_addr, &dst_len);
		if (bytes == -1) {
			perror("recv failed");
			exit(1);
		}
		else if (bytes > 0 && bytes != frame_size) {
			printf("Client exited\n");
			printf("Didn't recv the complete frame, bytes %ld\n",
				   bytes);
			exit(1);
		}
		else if (bytes == 0) {
			break;
		}
		rc = gettimeofday(&after, NULL);
		if (rc == -1) {
			perror("gettimeofday failed");
			exit(1);
		}
		cur_recv = after.tv_sec * 1000 * 1000 + after.tv_usec;
		memcpy((void *)&frame_ts, buf, sizeof(frame_ts));
		if (prev_frame_ts > 0) {
			int64_t d_variation = 0;

			d_variation = (int64_t)((cur_recv - prev_recv) -
									(frame_ts - prev_frame_ts));
			/* printf("Frame %u ts %llu d_variation %lld usecs\n",
			 i, frame_ts, d_variation);*/
			if (d_variation > 0) {
				if (min_variation == 0)
					min_variation = d_variation;
				else
					min_variation = ((min_variation <= d_variation) ?
									 min_variation : d_variation);
				max_variation = ((max_variation >= d_variation) ?
								 max_variation : d_variation);
				avg_variation += d_variation;
			} else {
				ignore_count++;
			}
		}
		prev_recv = cur_recv;
		prev_frame_ts = frame_ts;
		++i;
		/* Compute the time differenc */
		usecs = time_diff(&before, &after);
		DiffsBuf[i] = usecs;
		printf("<LOG>   :   Frame %d received after %lld usecs\n", i, usecs);
	}
	if (i != ignore_count)
		avg_variation = avg_variation / (i - ignore_count);
	else
		avg_variation = 0;
	printf("<LOG>   :   Received frames: %u\n", i);
	printf("<LOG>   :   Ignored frames: %u\n", ignore_count);
	printf("<LOG>   :   Minimum delay variation: %llu usecs\n", min_variation);
	printf("<LOG>   :   Maximum delay variation: %llu usecs\n", max_variation);
	printf("<LOG>   :   Average delay variation: %llu usecs\n", avg_variation);
	ShowStastics(DiffsBuf, num_frames);
}

/* Client */
void
tcpClient(int num_frames, int frame_size,
			   const char *buf, struct timespec sleep_time){
	int rc = 0, i = 0;
	ssize_t bytes;

	printf("<LOG>   :   TCP Client\n");
	so = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

	if (so <= 0) {
		perror("creating socket failed");
		exit(1);
	}
	srv_addr.sin_port = htons(srv_port);
	srv_addr.sin_len = sizeof(srv_addr);
	srv_addr.sin_family = AF_INET;
	rc = connect(so, (const struct sockaddr *)&srv_addr,
				 sizeof(srv_addr));
	if (rc != 0) {
		perror("connect failed");
		exit(1);
	}
	if (tc > 0) {
		rc = setsockopt(so, SOL_SOCKET, SO_TRAFFIC_CLASS, &tc,
						sizeof(tc));
		if (rc == -1) {
			perror("failed to set traffic class");
			exit(1);
		}
	}
	for (i = 0; i < num_frames; ++i) {
		struct timeval fts;
		uint64_t frame_ts;
		/* Add a timestamp to the frame */
		rc = gettimeofday(&fts, NULL);
		if (rc == -1) {
			perror("faile to get time of day");
			exit(1);
		}
		frame_ts = fts.tv_sec * 1000 * 1000 + fts.tv_usec;
		memcpy((void *)buf, (const void *)&frame_ts, sizeof(frame_ts));
		bytes = send(so, buf, frame_size, 0);
		if (bytes == -1) {
			perror("send failed \n");
			exit(1);
		}
		if (bytes != frame_size) {
			printf("failed to send all bytes, sent %ld\n", bytes);
			exit (1);
		}
		rc = nanosleep(&sleep_time, NULL);
		if (rc == -1) {
			perror("sleep failed");
			exit(1);
		}
		printf("<LOG>   :   Sent %u frames as a whole\n", (i + 1));
	}
}

void
udpClient(int num_frames, int frame_size,
			   const char *buf, struct timespec sleep_time){
	int rc = 0, i = 0;
	ssize_t bytes;

	printf("<LOG>   :   UDP Client\n");
	so = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (so <= 0) {
		perror("creating socket failed");
		exit(1);
	}
	srv_addr.sin_port = htons(srv_port);
	srv_addr.sin_len = sizeof(srv_addr);
	srv_addr.sin_family = AF_INET;
	if (tc > 0) {
		rc = setsockopt(so, SOL_SOCKET, SO_TRAFFIC_CLASS, &tc,
						sizeof(tc));
		if (rc == -1) {
			perror("failed to set traffic class");
			exit(1);
		}
	}
	for (i = 0; i < num_frames; ++i) {
		struct timeval fts;
		uint64_t frame_ts;
		/* Add a timestamp to the frame */
		rc = gettimeofday(&fts, NULL);
		if (rc == -1) {
			perror("faile to get time of day");
			exit(1);
		}
		frame_ts = fts.tv_sec * 1000 * 1000 + fts.tv_usec;
		memcpy((void *)buf, (const void *)&frame_ts, sizeof(frame_ts));
		bytes = sendto(so, buf, frame_size, 0, (struct sockaddr *)&srv_addr, sizeof(srv_addr));
		if (bytes == -1) {
			perror("send failed \n");
			exit(1);
		}
		if (bytes != frame_size) {
			printf("failed to send all bytes, sent %ld\n", bytes);
			exit (1);
		}
		rc = nanosleep(&sleep_time, NULL);
		if (rc == -1) {
			perror("sleep failed");
			exit(1);
		}
		printf("<LOG>   :   Sent %u frames as a whole\n", (i + 1));
	}
}