blob: f55e1071e8863f0a8086070fe13cc4e36eaf3685 [file] [log] [blame]
Jan Stanceke77bf552014-03-07 10:08:30 +01001/*
2 * Copyright (C) 2014 Linux Test Project, Inc.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it would be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 *
12 * Further, this software is distributed without any warranty that it
13 * is free of the rightful claim of any third person regarding
14 * infringement or the like. Any license provided herein, whether
15 * implied or otherwise, applies only to this software file. Patent
16 * licenses, if any, provided herein do not apply to combinations of
17 * this program with other software, or any other product whatsoever.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write the Free Software Foundation, Inc.
21 */
22
23#include <sys/types.h>
24#include <sys/socket.h>
25#include <netinet/in.h>
26
27#include "test.h"
28
29unsigned short tst_get_unused_port(void (cleanup_fn)(void),
30 unsigned short family, int type)
31{
32 int sock;
33 socklen_t slen;
34 struct sockaddr_storage _addr;
35 struct sockaddr *addr = (struct sockaddr *)&_addr;
36 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
37 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
38
39 switch (family) {
40 case AF_INET:
41 addr4->sin_family = AF_INET;
42 addr4->sin_port = 0;
43 addr4->sin_addr.s_addr = INADDR_ANY;
44 slen = sizeof(*addr4);
45 break;
46
47 case AF_INET6:
48 addr6->sin6_family = AF_INET6;
49 addr6->sin6_port = 0;
50 addr6->sin6_addr = in6addr_any;
51 slen = sizeof(*addr6);
52 break;
53
54 default:
55 tst_brkm(TBROK, cleanup_fn,
56 "tst_get_unused_port unknown family");
57 }
58
59 sock = socket(addr->sa_family, type, 0);
60 if (sock < 0)
61 tst_brkm(TBROK | TERRNO, cleanup_fn, "socket failed");
62
63 if (bind(sock, addr, slen) < 0)
64 tst_brkm(TBROK | TERRNO, cleanup_fn, "bind failed");
65
66 if (getsockname(sock, addr, &slen) == -1)
67 tst_brkm(TBROK | TERRNO, cleanup_fn, "getsockname failed");
68
69 if (close(sock) == -1)
70 tst_brkm(TBROK | TERRNO, cleanup_fn, "close failed");
71
72 switch (family) {
73 case AF_INET:
74 return addr4->sin_port;
75 case AF_INET6:
76 return addr6->sin6_port;
77 default:
78 return -1;
79 }
80}