OSDN Git Service

Merge remote-tracking branch 'toybox/master' into HEAD
[android-x86/external-toybox.git] / lib / net.c
1 #include "toys.h"
2
3 int xsocket(int domain, int type, int protocol)
4 {
5   int fd = socket(domain, type, protocol);
6
7   if (fd < 0) perror_exit("socket %x %x", type, protocol);
8   return fd;
9 }
10
11 void xsetsockopt(int fd, int level, int opt, void *val, socklen_t len)
12 {
13   if (-1 == setsockopt(fd, level, opt, val, len)) perror_exit("setsockopt");
14 }
15
16 int xconnect(char *host, char *port, int family, int socktype, int protocol,
17              int flags)
18 {
19   struct addrinfo info, *ai, *ai2;
20   int fd;
21
22   memset(&info, 0, sizeof(struct addrinfo));
23   info.ai_family = family;
24   info.ai_socktype = socktype;
25   info.ai_protocol = protocol;
26   info.ai_flags = flags;
27
28   fd = getaddrinfo(host, port, &info, &ai);
29   if (fd || !ai)
30     error_exit("Connect '%s%s%s': %s", host, port ? ":" : "", port ? port : "",
31       fd ? gai_strerror(fd) : "not found");
32
33   // Try all the returned addresses. Report errors if last entry can't connect.
34   for (ai2 = ai; ai; ai = ai->ai_next) {
35     fd = (ai->ai_next ? socket : xsocket)(ai->ai_family, ai->ai_socktype,
36       ai->ai_protocol);
37     if (!connect(fd, ai->ai_addr, ai->ai_addrlen)) break;
38     else if (!ai2->ai_next) perror_exit("connect");
39     close(fd);
40   }
41   freeaddrinfo(ai2);
42
43   return fd;
44 }
45
46 int xpoll(struct pollfd *fds, int nfds, int timeout)
47 {
48   int i;
49
50   for (;;) {
51     if (0>(i = poll(fds, nfds, timeout))) {
52       if (toys.signal) return i;
53       if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
54       else if (timeout>0) timeout--;
55     } else return i;
56   }
57 }