]> git.kaiwu.me - klib.git/commitdiff
Don't call freeaddrinfo() when getaddrinfo() fails
authorJohn Marshall <jm18@sanger.ac.uk>
Wed, 16 Apr 2014 13:07:03 +0000 (14:07 +0100)
committerJohn Marshall <jm18@sanger.ac.uk>
Thu, 23 Jul 2015 10:31:25 +0000 (11:31 +0100)
POSIX is somewhat unclear here, but doing so segfaults on some
platforms.  Hat tip Kamil Slowikowski @slowkow.

Instead print a more detailed error message using gai_strerror().

knetfile.c
kopen.c

index 158add91120b884a9e3644953221091aa73ef240..43ccb777d616e35807200051a7b6f47d527ce4ea 100644 (file)
@@ -87,7 +87,7 @@ static int socket_connect(const char *host, const char *port)
 {
 #define __err_connect(func) do { perror(func); freeaddrinfo(res); return -1; } while (0)
 
-       int on = 1, fd;
+       int ai_err, on = 1, fd;
        struct linger lng = { 0, 0 };
        struct addrinfo hints, *res = 0;
        memset(&hints, 0, sizeof(struct addrinfo));
@@ -95,7 +95,7 @@ static int socket_connect(const char *host, const char *port)
        hints.ai_socktype = SOCK_STREAM;
        /* In Unix/Mac, getaddrinfo() is the most convenient way to get
         * server information. */
-       if (getaddrinfo(host, port, &hints, &res) != 0) __err_connect("getaddrinfo");
+       if ((ai_err = getaddrinfo(host, port, &hints, &res)) != 0) { fprintf(stderr, "can't resolve %s:%s: %s\n", host, port, gai_strerror(ai_err)); return -1; }
        if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) __err_connect("socket");
        /* The following two setsockopt() are used by ftplib
         * (http://nbpfaus.net/~pfau/ftplib/). I am not sure if they
diff --git a/kopen.c b/kopen.c
index f72735c42b3c10a0b9d1f770e2b059762d77d19e..ad825da13f971ca827a960d9b3e0a38d8a7e60da 100644 (file)
--- a/kopen.c
+++ b/kopen.c
@@ -37,13 +37,13 @@ static int socket_connect(const char *host, const char *port)
 {
 #define __err_connect(func) do { perror(func); freeaddrinfo(res); return -1; } while (0)
 
-       int on = 1, fd;
+       int ai_err, on = 1, fd;
        struct linger lng = { 0, 0 };
        struct addrinfo hints, *res = 0;
        memset(&hints, 0, sizeof(struct addrinfo));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
-       if (getaddrinfo(host, port, &hints, &res) != 0) __err_connect("getaddrinfo");
+       if ((ai_err = getaddrinfo(host, port, &hints, &res)) != 0) { fprintf(stderr, "can't resolve %s:%s: %s\n", host, port, gai_strerror(ai_err)); return -1; }
        if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) __err_connect("socket");
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) __err_connect("setsockopt");
        if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &lng, sizeof(lng)) == -1) __err_connect("setsockopt");