iperf3-rs 1.0.1

Rust API for libiperf with live iperf3 metrics export
Documentation
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/*
 * iperf, Copyright (c) 2014-2023, The Regents of the University of
 * California, through Lawrence Berkeley National Laboratory (subject
 * to receipt of any required approvals from the U.S. Dept. of
 * Energy).  All rights reserved.
 *
 * If you have questions about your rights to use or distribute this
 * software, please contact Berkeley Lab's Technology Transfer
 * Department at TTD@lbl.gov.
 *
 * NOTICE.  This software is owned by the U.S. Department of Energy.
 * As such, the U.S. Government has been granted for itself and others
 * acting on its behalf a paid-up, nonexclusive, irrevocable,
 * worldwide license in the Software to reproduce, prepare derivative
 * works, and perform publicly and display publicly.  Beginning five
 * (5) years after the date permission to assert copyright is obtained
 * from the U.S. Department of Energy, and subject to any subsequent
 * five (5) year renewals, the U.S. Government is granted for itself
 * and others acting on its behalf a paid-up, nonexclusive,
 * irrevocable, worldwide license in the Software to reproduce,
 * prepare derivative works, distribute copies to the public, perform
 * publicly and display publicly, and to permit others to do so.
 *
 * This code is distributed under a BSD style license, see the LICENSE
 * file for complete information.
 */
#include "iperf_config.h"

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <assert.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#if defined(HAVE_UDP_SEGMENT) || defined(HAVE_UDP_GRO)
#include <linux/udp.h>
#endif

#ifdef HAVE_SENDFILE
#ifdef linux
#include <sys/sendfile.h>
#else
#ifdef __FreeBSD__
#include <sys/uio.h>
#else
#if defined(__APPLE__) && defined(__MACH__)	/* OS X */
#include <AvailabilityMacros.h>
#if defined(MAC_OS_X_VERSION_10_6)
#include <sys/uio.h>
#endif
#endif
#endif
#endif
#endif /* HAVE_SENDFILE */

#ifdef HAVE_IP_BOUND_IF
#include <netinet/in.h>
#endif /* HAVE_IP_BOUND_IF */

#ifdef HAVE_POLL_H
#include <poll.h>
#endif /* HAVE_POLL_H */

#include "iperf.h"
#include "iperf_util.h"
#include "net.h"
#include "timer.h"

static int nread_read_timeout = 10;
static int nread_overall_timeout = 30;

/*
 * Declaration of gerror in iperf_error.c.  Most other files in iperf3 can get this
 * by including "iperf.h", but net.c lives "below" this layer.  Clearly the
 * presence of this declaration is a sign we need to revisit this layering.
 */
extern int gerror;

/*
 * timeout_connect adapted from netcat, via OpenBSD and FreeBSD
 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
 */
int
timeout_connect(int s, const struct sockaddr *name, socklen_t namelen,
    int timeout)
{
	struct pollfd pfd;
	socklen_t optlen;
	int flags, optval;
	int ret;

	flags = 0;
	if (timeout != -1) {
		flags = fcntl(s, F_GETFL, 0);
		if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
			return -1;
	}

	if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
		pfd.fd = s;
		pfd.events = POLLOUT;
		if ((ret = poll(&pfd, 1, timeout)) == 1) {
			optlen = sizeof(optval);
			if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
			    &optval, &optlen)) == 0) {
				errno = optval;
				ret = optval == 0 ? 0 : -1;
			}
		} else if (ret == 0) {
			errno = ETIMEDOUT;
			ret = -1;
		} else
			ret = -1;
	}

	if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
		ret = -1;

	return (ret);
}

/* netdial and netannounce code comes from libtask: http://swtch.com/libtask/
 * Copyright: http://swtch.com/libtask/COPYRIGHT
*/

int
bind_to_device(int s, int domain, const char *bind_dev)
{
#if defined(HAVE_SO_BINDTODEVICE)
    return setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, bind_dev, IFNAMSIZ);
#elif defined(HAVE_IP_BOUND_IF)
    int opt;
    switch (domain) {
        case IPPROTO_IP:
            opt = IP_BOUND_IF;
            break;
        case IPPROTO_IPV6:
            opt = IPV6_BOUND_IF;
            break;
        default:
            errno = ENOTSUP;
            return -1;
    }
    int index = if_nametoindex(bind_dev);
    if (index == 0) {
        return -1;
    }
    return setsockopt(s, domain, opt, &index, sizeof(index));
#else
    errno = ENOTSUP;
    return -1;
#endif
}

/* create a socket */
int
create_socket(int domain, int type, int proto, const char *local, const char *bind_dev, int local_port, const char *server, int port, struct addrinfo **server_res_out)
{
    struct addrinfo hints, *local_res = NULL, *server_res = NULL;
    int s, saved_errno;
    char portstr[6];

    if (local) {
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = domain;
        hints.ai_socktype = type;
        if ((gerror = getaddrinfo(local, NULL, &hints, &local_res)) != 0)
            return -1;
    }

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = domain;
    hints.ai_socktype = type;
    snprintf(portstr, sizeof(portstr), "%d", port);
    if ((gerror = getaddrinfo(server, portstr, &hints, &server_res)) != 0) {
	if (local)
	    freeaddrinfo(local_res);
        return -1;
    }

    s = socket(server_res->ai_family, type, proto);
    if (s < 0) {
	if (local)
	    freeaddrinfo(local_res);
	freeaddrinfo(server_res);
        return -1;
    }

    if (bind_dev) {
        if (bind_to_device(s, domain, bind_dev) < 0) {
            saved_errno = errno;
            close(s);
            freeaddrinfo(local_res);
            freeaddrinfo(server_res);
            errno = saved_errno;
            return -1;
        }
    }

    /* Bind the local address if given a name (with or without --cport) */
    if (local) {
        if (local_port) {
            struct sockaddr_in *lcladdr;
            lcladdr = (struct sockaddr_in *)local_res->ai_addr;
            lcladdr->sin_port = htons(local_port);
        }

        if (bind(s, (struct sockaddr *) local_res->ai_addr, local_res->ai_addrlen) < 0) {
	    saved_errno = errno;
	    close(s);
	    freeaddrinfo(local_res);
	    freeaddrinfo(server_res);
	    errno = saved_errno;
            return -1;
	}
        freeaddrinfo(local_res);
    }
    /* No local name, but --cport given */
    else if (local_port) {
	size_t addrlen;
	struct sockaddr_storage lcl;

	/* IPv4 */
	if (server_res->ai_family == AF_INET) {
	    struct sockaddr_in *lcladdr = (struct sockaddr_in *) &lcl;
	    lcladdr->sin_family = AF_INET;
	    lcladdr->sin_port = htons(local_port);
	    lcladdr->sin_addr.s_addr = INADDR_ANY;
	    addrlen = sizeof(struct sockaddr_in);
	}
	/* IPv6 */
	else if (server_res->ai_family == AF_INET6) {
	    struct sockaddr_in6 *lcladdr = (struct sockaddr_in6 *) &lcl;
	    lcladdr->sin6_family = AF_INET6;
	    lcladdr->sin6_port = htons(local_port);
	    lcladdr->sin6_addr = in6addr_any;
	    addrlen = sizeof(struct sockaddr_in6);
	}
	/* Unknown protocol */
	else {
	    close(s);
	    freeaddrinfo(server_res);
	    errno = EAFNOSUPPORT;
            return -1;
	}

        if (bind(s, (struct sockaddr *) &lcl, addrlen) < 0) {
	    saved_errno = errno;
	    close(s);
	    freeaddrinfo(server_res);
	    errno = saved_errno;
            return -1;
        }
    }

    *server_res_out = server_res;
    return s;
}

/* make connection to server */
int
netdial(int domain, int proto, const char *local, const char *bind_dev, int local_port, const char *server, int port, int timeout)
{
    struct addrinfo *server_res = NULL;
    int s, saved_errno;

    s = create_socket(domain, proto, 0, local, bind_dev, local_port, server, port, &server_res);
    if (s < 0) {
      return -1;
    }

    if (timeout_connect(s, (struct sockaddr *) server_res->ai_addr, server_res->ai_addrlen, timeout) < 0 && errno != EINPROGRESS) {
	saved_errno = errno;
	close(s);
	freeaddrinfo(server_res);
	errno = saved_errno;
        return -1;
    }

    freeaddrinfo(server_res);
    return s;
}

/***************************************************************/

int
netannounce(int domain, int proto, const char *local, const char *bind_dev, int port)
{
    struct addrinfo hints, *res;
    char portstr[6];
    int s, opt, saved_errno;

    snprintf(portstr, 6, "%d", port);
    memset(&hints, 0, sizeof(hints));
    /*
     * If binding to the wildcard address with no explicit address
     * family specified, then force us to get an AF_INET6 socket.  On
     * CentOS 6 and MacOS, getaddrinfo(3) with AF_UNSPEC in ai_family,
     * and ai_flags containing AI_PASSIVE returns a result structure
     * with ai_family set to AF_INET, with the result that we create
     * and bind an IPv4 address wildcard address and by default, we
     * can't accept IPv6 connections.
     *
     * On FreeBSD, under the above circumstances, ai_family in the
     * result structure is set to AF_INET6.
     */
    if (domain == AF_UNSPEC && !local) {
	hints.ai_family = AF_INET6;
    }
    else {
	hints.ai_family = domain;
    }
    hints.ai_socktype = proto;
    hints.ai_flags = AI_PASSIVE;
    if ((gerror = getaddrinfo(local, portstr, &hints, &res)) != 0)
        return -1;

    s = socket(res->ai_family, proto, 0);
    if (s < 0) {
	freeaddrinfo(res);
        return -1;
    }

    if (bind_dev) {
#if defined(HAVE_SO_BINDTODEVICE)
        if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE,
                       bind_dev, IFNAMSIZ) < 0)
#endif // HAVE_SO_BINDTODEVICE
        {
            saved_errno = errno;
            close(s);
            freeaddrinfo(res);
            errno = saved_errno;
            return -1;
        }
    }

    opt = 1;
    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
		   (char *) &opt, sizeof(opt)) < 0) {
	saved_errno = errno;
	close(s);
	freeaddrinfo(res);
	errno = saved_errno;
	return -1;
    }
    /*
     * If we got an IPv6 socket, figure out if it should accept IPv4
     * connections as well.  We do that if and only if no address
     * family was specified explicitly.  Note that we can only
     * do this if the IPV6_V6ONLY socket option is supported.  Also,
     * OpenBSD explicitly omits support for IPv4-mapped addresses,
     * even though it implements IPV6_V6ONLY.
     */
#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
    if (res->ai_family == AF_INET6 && (domain == AF_UNSPEC || domain == AF_INET6)) {
	if (domain == AF_UNSPEC)
	    opt = 0;
	else
	    opt = 1;
	if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
		       (char *) &opt, sizeof(opt)) < 0) {
	    saved_errno = errno;
	    close(s);
	    freeaddrinfo(res);
	    errno = saved_errno;
	    return -1;
	}
    }
#endif /* IPV6_V6ONLY */

    if (bind(s, (struct sockaddr *) res->ai_addr, res->ai_addrlen) < 0) {
        saved_errno = errno;
        close(s);
	freeaddrinfo(res);
        errno = saved_errno;
        return -1;
    }

    freeaddrinfo(res);

    if (proto == SOCK_STREAM) {
        if (listen(s, INT_MAX) < 0) {
	    saved_errno = errno;
	    close(s);
	    errno = saved_errno;
            return -1;
        }
    }

    return s;
}

/*******************************************************************/
/* Nread - reads 'count' bytes from a socket  */
/********************************************************************/

int
Nread(int fd, char *buf, size_t count, int prot)
{
    return Nrecv(fd, buf, count, prot, 0);
}

/*******************************************************************/
/* Nrecv - reads 'count' bytes from a socket  */
/********************************************************************/

int
Nrecv(int fd, char *buf, size_t count, int prot, int sock_opt)
{
    register ssize_t r;
    register size_t nleft = count;
    struct iperf_time ftimeout = { 0, 0 };

    fd_set rfdset;
    struct timeval timeout = { nread_read_timeout, 0 };

    /*
     * fd might not be ready for reading on entry. Check for this
     * (with timeout) first.
     *
     * This check could go inside the while() loop below, except we're
     * currently considering whether it might make sense to support a
     * codepath that bypasses this check, for situations where we
     * already know that fd has data on it (for example if we'd gotten
     * to here as the result of a select() call.
     */
    {
        FD_ZERO(&rfdset);
        FD_SET(fd, &rfdset);
        r = select(fd + 1, &rfdset, NULL, NULL, &timeout);
        if (r < 0) {
            return NET_HARDERROR;
        }
        if (r == 0) {
            return 0;
        }
    }

    while (nleft > 0) {
        if (sock_opt)
            r = recv(fd, buf, nleft, sock_opt);
        else
            r = read(fd, buf, nleft);

        if (r < 0) {
            /* XXX EWOULDBLOCK can't happen without non-blocking sockets */
            if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
                break;
            else
                return NET_HARDERROR;
        } else if (r == 0)
            break;

	if (sock_opt & MSG_TRUNC) {
            size_t bytes_copied = (r > nleft)? nleft: r;
            nleft -= bytes_copied;
            buf += bytes_copied;
        }
	else {
            nleft -= r;
            buf += r;
        }

        /*
         * We need some more bytes but don't want to wait around
         * forever for them. In the case of partial results, we need
         * to be able to read some bytes every nread_timeout seconds.
         */
        if (nleft > 0) {
            struct iperf_time now;

            /*
             * Also, we have an approximate upper limit for the total time
             * that a Nread call is supposed to take. We trade off accuracy
             * of this timeout for a hopefully lower performance impact.
             */
            iperf_time_now(&now);
            if (ftimeout.secs == 0) {
                ftimeout = now;
                iperf_time_add_usecs(&ftimeout, nread_overall_timeout * 1000000L);
            }
            if (iperf_time_compare(&ftimeout, &now) < 0) {
                break;
            }

            FD_ZERO(&rfdset);
            FD_SET(fd, &rfdset);
            r = select(fd + 1, &rfdset, NULL, NULL, &timeout);
            if (r < 0) {
                return NET_HARDERROR;
            }
            if (r == 0) {
                break;
            }
        }
    }
    return count - nleft;
}

/********************************************************************/
/* Nreads 'count' bytes from a socket - but without using select()   */
/********************************************************************/
int
Nread_no_select(int fd, char *buf, size_t count, int prot)
{
    return Nrecv_no_select(fd, buf, count, prot, 0);
}

/********************************************************************/
/* Nrecv reads 'count' bytes from a socket - but without using select()   */
/********************************************************************/
int
Nrecv_no_select(int fd, char *buf, size_t count, int prot, int sock_opt)
{
    register ssize_t r;
    register size_t nleft = count;

    while (nleft > 0) {
        if (sock_opt)
            r = recv(fd, buf, nleft, sock_opt);
        else
            r = read(fd, buf, nleft);

        if (r < 0) {
            /* XXX EWOULDBLOCK can't happen without non-blocking sockets */
            if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
                break;
            else
                return NET_HARDERROR;
        } else if (r == 0)
            break;

	if (sock_opt & MSG_TRUNC) {
            size_t bytes_copied = (r > nleft)? nleft: r;
            nleft -= bytes_copied;
            buf += bytes_copied;
        }
	else {
            nleft -= r;
            buf += r;
        }


    }
    return count - nleft;
}

#ifdef HAVE_UDP_GRO
static int recv_msg_gro(int fd, char *buf, int len, int *gso_size)
{
	char control[CMSG_SPACE(sizeof(uint16_t))] = {0};
	struct msghdr msg = {0};
	struct iovec iov = {0};
	struct cmsghdr *cmsg;
	uint16_t *gsosizeptr;
	int ret;

	/* Input validation */
	if (!buf || len <= 0 || !gso_size) {
		return -1;
	}

	iov.iov_base = buf;
	iov.iov_len = len;

	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;

	msg.msg_control = control;
	msg.msg_controllen = sizeof(control);

	*gso_size = -1;
	ret = recvmsg(fd, &msg, MSG_DONTWAIT);

	if (ret > 0) {
		for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
			if (cmsg->cmsg_level == IPPROTO_UDP && cmsg->cmsg_type == UDP_GRO) {
				/* Validate cmsg data length */
				if (cmsg->cmsg_len >= CMSG_LEN(sizeof(uint16_t))) {
					gsosizeptr = (uint16_t *) CMSG_DATA(cmsg);
					*gso_size = *gsosizeptr;
					/* Sanity check the gso_size value */
					if (*gso_size <= 0 || *gso_size > len) {
						*gso_size = -1;  /* Mark as invalid */
					}
				}
				break;
			}
		}
	}

	return ret;
}

int
Nread_gro(int fd, char *buf, size_t count, int prot, int *dgram_sz)
{
	register ssize_t r;

	/* Input validation */
	if (!buf || count <= 0 || !dgram_sz) {
		return NET_HARDERROR;
	}

	/* Limit maximum buffer size to prevent excessive memory usage */
	if (count > MAX_UDP_BLOCKSIZE) {
		count = MAX_UDP_BLOCKSIZE;
	}

	r = recv_msg_gro(fd, buf, count, dgram_sz);

	if (r < 0) {
		if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
			return 0;
		} else {
			return NET_HARDERROR;
		}
	}

	/* Additional validation of returned dgram_sz */
	if (r > 0 && *dgram_sz > 0 && *dgram_sz > r) {
		/* dgram_sz shouldn't be larger than actual received data */
		*dgram_sz = r;
	}

	return r;
}
#else
int
Nread_gro(int fd, char *buf, size_t count, int prot, int *dgram_sz)
{
	/* GRO not supported on this platform */
	return NET_HARDERROR;
}
#endif /* HAVE_UDP_GRO */

/*
 *                      N W R I T E
 */

int
Nwrite(int fd, const char *buf, size_t count, int prot)
{
    register ssize_t r;
    register size_t nleft = count;

    while (nleft > 0) {
	r = write(fd, buf, nleft);
	if (r < 0) {
	    switch (errno) {
		case EINTR:
		case EAGAIN:
#if (EAGAIN != EWOULDBLOCK)
                    /* XXX EWOULDBLOCK can't happen without non-blocking sockets */
		case EWOULDBLOCK:
#endif
		if (count == nleft)
		    return NET_SOFTERROR;
		return count - nleft;

                case ENOBUFS :
                return NET_SOFTERROR;

                default:
		return NET_HARDERROR;
	    }
	} else if (r == 0)
	    return NET_SOFTERROR;
	nleft -= r;
	buf += r;
    }
    return count;
}

#ifdef HAVE_UDP_SEGMENT
static void udp_msg_gso(struct cmsghdr *cm, uint16_t gso_size)
{
	uint16_t *valp;

	cm->cmsg_level = IPPROTO_UDP;
	cm->cmsg_type = UDP_SEGMENT;
	cm->cmsg_len = CMSG_LEN(sizeof(gso_size));
	valp = (void *) CMSG_DATA(cm);
	*valp = gso_size;
}

static int udp_sendmsg_gso(int fd, const char *buf, size_t count, uint16_t gso_size)
{
	char control[CMSG_SPACE(sizeof(gso_size))] = {0};
	struct msghdr msg = {0};
	struct iovec iov = {0};
	size_t msg_controllen;
	struct cmsghdr *cmsg;
	int ret;

	iov.iov_base = (void *) buf;
	iov.iov_len = count;

	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;

	msg.msg_control = control;
	msg.msg_controllen = sizeof(control);
	cmsg = CMSG_FIRSTHDR(&msg);

	udp_msg_gso(cmsg, gso_size);

	msg_controllen = CMSG_SPACE(sizeof(gso_size));
	msg.msg_controllen = msg_controllen;

	ret = sendmsg(fd, &msg, 0);

	return ret;
}

int
Nwrite_gso(int fd, const char *buf, size_t count, int prot, uint16_t gso_size)
{
	register ssize_t r;

	r = udp_sendmsg_gso(fd, buf, count, gso_size);

	if (r < 0) {
		switch (errno) {
			case EINTR:
			case EAGAIN:
#if (EAGAIN != EWOULDBLOCK)
			case EWOULDBLOCK:
#endif
				return 0;

			case ENOBUFS:
				return NET_SOFTERROR;

			default:
				return NET_HARDERROR;
		}
	}
	return r;
}
#else
int
Nwrite_gso(int fd, const char *buf, size_t count, int prot, uint16_t gso_size)
{
	/* GSO not supported on this platform */
	return NET_HARDERROR;
}
#endif /* HAVE_UDP_SEGMENT */

int
has_sendfile(void)
{
#if defined(HAVE_SENDFILE)
    return 1;
#else /* HAVE_SENDFILE */
    return 0;
#endif /* HAVE_SENDFILE */

}


/*
 *                      N S E N D F I L E
 */

int
Nsendfile(int fromfd, int tofd, const char *buf, size_t count)
{
#if defined(HAVE_SENDFILE)
    off_t offset;
#if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__) && defined(MAC_OS_X_VERSION_10_6))
    off_t sent;
#endif
    register size_t nleft;
    register ssize_t r;

    nleft = count;
    while (nleft > 0) {
	offset = count - nleft;
#ifdef linux
	r = sendfile(tofd, fromfd, &offset, nleft);
	if (r > 0)
	    nleft -= r;
#elif defined(__FreeBSD__)
	r = sendfile(fromfd, tofd, offset, nleft, NULL, &sent, 0);
	nleft -= sent;
#elif defined(__APPLE__) && defined(__MACH__) && defined(MAC_OS_X_VERSION_10_6)	/* OS X */
	sent = nleft;
	r = sendfile(fromfd, tofd, offset, &sent, NULL, 0);
	nleft -= sent;
#else
	/* Shouldn't happen. */
	r = -1;
	errno = ENOSYS;
#endif
	if (r < 0) {
	    switch (errno) {
		case EINTR:
		case EAGAIN:
#if (EAGAIN != EWOULDBLOCK)
                    /* XXX EWOULDBLOCK can't happen without non-blocking sockets */
		case EWOULDBLOCK:
#endif
		if (count == nleft)
		    return NET_SOFTERROR;
		return count - nleft;

		case ENOBUFS:
		case ENOMEM:
		return NET_SOFTERROR;

		default:
		return NET_HARDERROR;
	    }
	}
#ifdef linux
	else if (r == 0)
	    return NET_SOFTERROR;
#endif
    }
    return count;
#else /* HAVE_SENDFILE */
    errno = ENOSYS;	/* error if somehow get called without HAVE_SENDFILE */
    return NET_HARDERROR;
#endif /* HAVE_SENDFILE */
}

/*************************************************************************/

int
setnonblocking(int fd, int nonblocking)
{
    int flags, newflags;

    flags = fcntl(fd, F_GETFL, 0);
    if (flags < 0) {
        perror("fcntl(F_GETFL)");
        return -1;
    }
    if (nonblocking)
	newflags = flags | (int) O_NONBLOCK;
    else
	newflags = flags & ~((int) O_NONBLOCK);
    if (newflags != flags)
	if (fcntl(fd, F_SETFL, newflags) < 0) {
	    perror("fcntl(F_SETFL)");
	    return -1;
	}
    return 0;
}

/****************************************************************************/

int
getsockdomain(int sock)
{
    struct sockaddr_storage sa;
    socklen_t len = sizeof(sa);

    if (getsockname(sock, (struct sockaddr *)&sa, &len) < 0) {
        return -1;
    }
    return ((struct sockaddr *) &sa)->sa_family;
}

/****************************************************************************/

// Sync and close a socket
void
iperf_sync_close_socket(int sock)
{
#ifdef HAVE_SOCKET_SHUTDOWN_SHUT_WR
    char buffer[128];
    shutdown(sock, SHUT_WR); // Signal that we are done writing
    while (Nread(sock, buffer, sizeof(buffer), 0) > 0); // Read until EOF
#else // HAVE_SOCKET_SHUTDOWN_SHUT_WR
    sleep(1); // Not the best mechanism, but should be good enough for error cases (and is simple and portable)
#endif // HAVE_SOCKET_SHUTDOWN_SHUT_WR
    close(sock);
}