]> git.proxmox.com Git - mirror_qemu.git/blame - tests/socket-helpers.c
sockets: pull code for testing IP availability out of specific test
[mirror_qemu.git] / tests / socket-helpers.c
CommitLineData
9b589ffb
DB
1/*
2 * Helper functions for tests using sockets
3 *
4 * Copyright 2015-2018 Red Hat, Inc.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 or
9 * (at your option) version 3 of the License.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21#include "qemu/osdep.h"
22#include "qemu-common.h"
23#include "qemu/sockets.h"
24#include "socket-helpers.h"
25
26#ifndef AI_ADDRCONFIG
27# define AI_ADDRCONFIG 0
28#endif
29#ifndef EAI_ADDRFAMILY
30# define EAI_ADDRFAMILY 0
31#endif
32
33int socket_can_bind(const char *hostname)
34{
35 int fd = -1;
36 struct addrinfo ai, *res = NULL;
37 int rc;
38 int ret = -1;
39
40 memset(&ai, 0, sizeof(ai));
41 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
42 ai.ai_family = AF_UNSPEC;
43 ai.ai_socktype = SOCK_STREAM;
44
45 /* lookup */
46 rc = getaddrinfo(hostname, NULL, &ai, &res);
47 if (rc != 0) {
48 if (rc == EAI_ADDRFAMILY ||
49 rc == EAI_FAMILY) {
50 errno = EADDRNOTAVAIL;
51 } else {
52 errno = EINVAL;
53 }
54 goto cleanup;
55 }
56
57 fd = qemu_socket(res->ai_family, res->ai_socktype, res->ai_protocol);
58 if (fd < 0) {
59 goto cleanup;
60 }
61
62 if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) {
63 goto cleanup;
64 }
65
66 ret = 0;
67
68 cleanup:
69 if (fd != -1) {
70 close(fd);
71 }
72 if (res) {
73 freeaddrinfo(res);
74 }
75 return ret;
76}
77
78
79int socket_check_protocol_support(bool *has_ipv4, bool *has_ipv6)
80{
81 *has_ipv4 = *has_ipv6 = false;
82
83 if (socket_can_bind("127.0.0.1") < 0) {
84 if (errno != EADDRNOTAVAIL) {
85 return -1;
86 }
87 } else {
88 *has_ipv4 = true;
89 }
90
91 if (socket_can_bind("::1") < 0) {
92 if (errno != EADDRNOTAVAIL) {
93 return -1;
94 }
95 } else {
96 *has_ipv6 = true;
97 }
98
99 return 0;
100}