Skip to content

Commit 935f417

Browse files
hfmansonvanrein
authored andcommitted
use getaddrinfo in testsrv.c
1 parent e0fdf3a commit 935f417

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

tool/testsrv.c

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <string.h>
66
#include <stdint.h>
77

8+
89
#include <unistd.h>
910
#include <poll.h>
1011
#include <errno.h>
@@ -13,6 +14,7 @@
1314
#include <sys/types.h>
1415
#include <sys/socket.h>
1516
#include <netinet/in.h>
17+
#include <netdb.h>
1618

1719
#include <tlspool/starttls.h>
1820

@@ -42,12 +44,19 @@ void sigcont_handler (int signum) {
4244
}
4345

4446
int main (int argc, char **argv) {
45-
int sox, cnx;
47+
int sox, cnx, rc;
4648
int plainfd;
47-
struct sockaddr_in6 sin6;
49+
const char *host = argc < 2 ? "::" : argv[1];
50+
const char *service = argc < 3 ? "12345" : argv[2];
51+
struct addrinfo *res;
4852
sigset_t sigcontset;
4953
uint8_t rndbuf [16];
5054

55+
rc = getaddrinfo(host, service, NULL, &res);
56+
if (rc != 0) {
57+
fprintf(stderr, "Error in getaddrinfo: %s\n", gai_strerror(rc));
58+
exit (1);
59+
}
5160
if (sigemptyset (&sigcontset) ||
5261
sigaddset (&sigcontset, SIGCONT) ||
5362
pthread_sigmask (SIG_BLOCK, &sigcontset, NULL)) {
@@ -56,16 +65,12 @@ int main (int argc, char **argv) {
5665
}
5766

5867
reconnect:
59-
sox = socket (AF_INET6, SOCK_STREAM, 0);
68+
sox = socket (res->ai_family, SOCK_STREAM, 0);
6069
if (sox == -1) {
6170
perror ("Failed to create socket on testsrv");
6271
exit (1);
6372
}
64-
memset (&sin6, 0, sizeof (sin6));
65-
sin6.sin6_family = AF_INET6;
66-
sin6.sin6_port = htons (12345);
67-
memcpy (&sin6.sin6_addr, &in6addr_loopback, 16);
68-
if (bind (sox, (struct sockaddr *) &sin6, sizeof (sin6)) == -1) {
73+
if (bind (sox, res->ai_addr, res->ai_addrlen) == -1) {
6974
perror ("Socket failed to bind on testsrv");
7075
if (errno == EADDRINUSE) {
7176
close (sox);
@@ -133,6 +138,7 @@ int main (int argc, char **argv) {
133138
exit (1);
134139
}
135140
}
141+
freeaddrinfo(res);
136142
return 0;
137143
}
138144

0 commit comments

Comments
 (0)