aboutsummaryrefslogtreecommitdiff
path: root/testcases/lib/tst_get_unused_port.c
blob: a843cc6e3c7897bb1205e94957ed8424d86ff4c1 (plain)
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
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (c) 2014 Oracle and/or its affiliates. All Rights Reserved.
 * Copyright (c) 2019 Petr Vorel <pvorel@suse.cz>
 * Author: Alexey Kodanev <alexey.kodanev@oracle.com>
 */

#define TST_NO_DEFAULT_MAIN
#include <stdio.h>

#include "tst_safe_net.h"
#include "tst_test.h"

static void help(const char *fname)
{
	printf("usage: %s FAMILY TYPE\n", fname);
	printf("FAMILY := { ipv4 | ipv6 }\n");
	printf("TYPE := { stream | dgram }\n");
}

int main(int argc, char *argv[])
{
	int family = 0, type = 0;
	int opt;

	while ((opt = getopt(argc, argv, ":h")) != -1) {
		switch (opt) {
		case 'h':
			help(argv[0]);
			return 0;
		default:
			help(argv[0]);
			return 1;
		}
	}

	if (argc != 3) {
		help(argv[0]);
		return 1;
	}

	if (!strcmp(argv[1], "ipv4"))
		family = AF_INET;
	else if (!strcmp(argv[1], "ipv6"))
		family = AF_INET6;

	if (!strcmp(argv[2], "stream"))
		type = SOCK_STREAM;
	else if (!strcmp(argv[2], "dgram"))
		type = SOCK_DGRAM;

	if (!family || !type) {
		help(argv[0]);
		return 1;
	}

	printf("%d", ntohs(TST_GET_UNUSED_PORT(family, type)));
	return 0;
}