2 * Helper functions for tests using sockets
4 * Copyright 2015-2018 Red Hat, Inc.
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.
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.
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/>.
21 #include "qemu/osdep.h"
22 #include "qemu-common.h"
23 #include "qemu/sockets.h"
24 #include "socket-helpers.h"
27 # define AI_ADDRCONFIG 0
29 #ifndef EAI_ADDRFAMILY
30 # define EAI_ADDRFAMILY 0
33 int socket_can_bind_connect(const char *hostname
)
35 int lfd
= -1, cfd
= -1, afd
= -1;
36 struct addrinfo ai
, *res
= NULL
;
37 struct sockaddr_storage ss
;
38 socklen_t sslen
= sizeof(ss
);
40 socklen_t soerrlen
= sizeof(soerr
);
41 bool check_soerr
= false;
45 memset(&ai
, 0, sizeof(ai
));
46 ai
.ai_flags
= AI_CANONNAME
| AI_ADDRCONFIG
;
47 ai
.ai_family
= AF_UNSPEC
;
48 ai
.ai_socktype
= SOCK_STREAM
;
51 rc
= getaddrinfo(hostname
, NULL
, &ai
, &res
);
53 if (rc
== EAI_ADDRFAMILY
||
55 errno
= EADDRNOTAVAIL
;
62 lfd
= qemu_socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
);
67 cfd
= qemu_socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
);
72 if (bind(lfd
, res
->ai_addr
, res
->ai_addrlen
) < 0) {
76 if (listen(lfd
, 1) < 0) {
80 if (getsockname(lfd
, (struct sockaddr
*)&ss
, &sslen
) < 0) {
84 qemu_set_nonblock(cfd
);
85 if (connect(cfd
, (struct sockaddr
*)&ss
, sslen
) < 0) {
86 if (errno
== EINPROGRESS
) {
94 afd
= accept(lfd
, (struct sockaddr
*)&ss
, &sslen
);
100 if (qemu_getsockopt(cfd
, SOL_SOCKET
, SO_ERROR
, &soerr
, &soerrlen
) < 0) {
128 int socket_check_protocol_support(bool *has_ipv4
, bool *has_ipv6
)
130 *has_ipv4
= *has_ipv6
= false;
132 if (socket_can_bind_connect("127.0.0.1") < 0) {
133 if (errno
!= EADDRNOTAVAIL
) {
140 if (socket_can_bind_connect("::1") < 0) {
141 if (errno
!= EADDRNOTAVAIL
) {