2013-04-26 00:41:05 -07:00
|
|
|
#include "toys.h"
|
|
|
|
|
|
|
|
int xsocket(int domain, int type, int protocol)
|
|
|
|
{
|
|
|
|
int fd = socket(domain, type, protocol);
|
|
|
|
|
|
|
|
if (fd < 0) perror_exit("socket %x %x", type, protocol);
|
|
|
|
return fd;
|
|
|
|
}
|
2015-04-27 09:13:19 -07:00
|
|
|
|
|
|
|
void xsetsockopt(int fd, int level, int opt, void *val, socklen_t len)
|
|
|
|
{
|
|
|
|
if (-1 == setsockopt(fd, level, opt, val, len)) perror_exit("setsockopt");
|
|
|
|
}
|
2015-08-03 12:34:01 -07:00
|
|
|
|
2015-08-05 18:32:49 -07:00
|
|
|
int xconnect(char *host, char *port, int family, int socktype, int protocol,
|
2015-08-03 12:34:01 -07:00
|
|
|
int flags)
|
|
|
|
{
|
2015-08-05 19:20:27 -07:00
|
|
|
struct addrinfo info, *ai, *ai2;
|
2015-08-03 12:34:01 -07:00
|
|
|
int fd;
|
|
|
|
|
|
|
|
memset(&info, 0, sizeof(struct addrinfo));
|
|
|
|
info.ai_family = family;
|
|
|
|
info.ai_socktype = socktype;
|
|
|
|
info.ai_protocol = protocol;
|
|
|
|
info.ai_flags = flags;
|
|
|
|
|
2015-08-05 18:32:49 -07:00
|
|
|
fd = getaddrinfo(host, port, &info, &ai);
|
2015-08-03 12:34:01 -07:00
|
|
|
if (fd || !ai)
|
2015-08-05 18:32:49 -07:00
|
|
|
error_exit("Connect '%s%s%s': %s", host, port ? ":" : "", port ? port : "",
|
2015-08-03 12:34:01 -07:00
|
|
|
fd ? gai_strerror(fd) : "not found");
|
|
|
|
|
2015-08-05 19:20:27 -07:00
|
|
|
// Try all the returned addresses. Report errors if last entry can't connect.
|
|
|
|
for (ai2 = ai; ai; ai = ai->ai_next) {
|
|
|
|
fd = (ai->ai_next ? socket : xsocket)(ai->ai_family, ai->ai_socktype,
|
|
|
|
ai->ai_protocol);
|
|
|
|
if (!connect(fd, ai->ai_addr, ai->ai_addrlen)) break;
|
|
|
|
else if (!ai2->ai_next) perror_exit("connect");
|
|
|
|
close(fd);
|
|
|
|
}
|
|
|
|
freeaddrinfo(ai2);
|
2015-08-03 12:34:01 -07:00
|
|
|
|
|
|
|
return fd;
|
|
|
|
}
|
2016-01-16 14:59:47 -08:00
|
|
|
|
|
|
|
int xpoll(struct pollfd *fds, int nfds, int timeout)
|
|
|
|
{
|
|
|
|
int i;
|
|
|
|
|
|
|
|
for (;;) {
|
|
|
|
if (0>(i = poll(fds, nfds, timeout))) {
|
2016-01-28 20:10:06 -08:00
|
|
|
if (toys.signal) return i;
|
2016-01-16 14:59:47 -08:00
|
|
|
if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
|
|
|
|
else if (timeout>0) timeout--;
|
|
|
|
} else return i;
|
|
|
|
}
|
|
|
|
}
|