/*
* Empire - A multi-player, client/server Internet based war game.
- * Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
+ * Copyright (C) 1986-2013, Dave Pare, Jeff Bailey, Thomas Ruschak,
* Ken Stevens, Steve McClure, Markus Armbruster
*
* Empire is free software: you can redistribute it and/or modify
* tcp_listen.c: Create a socket and listen on it
*
* Known contributors to this file:
- * Markus Armbruster, 2005-2009
+ * Markus Armbruster, 2005-2010
*/
#include <config.h>
+#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
* Inspired by example code from W. Richard Stevens: UNIX Network
* Programming, Vol. 1
*/
- int n;
- struct addrinfo hints, *res, *ressave;
+ int err;
+ struct addrinfo hints, *first_ai, *ai;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
- if ((n = getaddrinfo(host, serv, &hints, &res)) != 0)
- cant_listen(host, serv, gai_strerror(n));
- ressave = res;
+ if ((err = getaddrinfo(host, serv, &hints, &first_ai)) != 0)
+ cant_listen(host, serv, gai_strerror(err));
+ assert(first_ai);
- do {
- fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
+ for (ai = first_ai; ai; ai = ai->ai_next) {
+ fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd < 0)
continue; /* error, try next one */
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
- cant_listen(host, serv, strerror(errno));
- if (bind(fd, res->ai_addr, res->ai_addrlen) == 0)
+#ifdef IPV6_V6ONLY
+ if (ai->ai_family == AF_INET6) {
+ int off = 0;
+
+ setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off));
+ }
+#endif
+
+ setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
+ if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0)
break; /* success */
close(fd); /* error, close and try next one */
- } while ((res = res->ai_next) != NULL);
+ }
- if (res == NULL) /* errno from final socket() or bind() */
+ if (ai == NULL) /* errno from final socket() or bind() */
cant_listen(host, serv, strerror(errno));
if (listen(fd, SOMAXCONN) < 0)
cant_listen(host, serv, strerror(errno));
if (addrlenp)
- *addrlenp = res->ai_addrlen;
+ *addrlenp = ai->ai_addrlen;
- freeaddrinfo(ressave);
+ freeaddrinfo(first_ai);
#else /* !HAVE_GETADDRINFO */
struct sockaddr_in sin;
}
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
cant_listen(host, serv, strerror(errno));
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
- cant_listen(host, serv, strerror(errno));
+ setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
cant_listen(host, serv, strerror(errno));
if (listen(fd, SOMAXCONN) < 0)