Brad Campbell <brad@seme.com.au> notes that
[oweals/busybox.git] / libbb / xconnect.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Connect to host at port using address resolusion from getaddrinfo
6  *
7  */
8
9 #include <unistd.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <netdb.h>
15 #include <netinet/in.h>
16 #include "libbb.h"
17
18 int xconnect(const char *host, const char *port)
19 {
20 #if CONFIG_FEATURE_IPV6
21         struct addrinfo hints;
22         struct addrinfo *res;
23         struct addrinfo *addr_info;
24         int error;
25         int s;
26
27         memset(&hints, 0, sizeof(hints));
28         /* set-up hints structure */
29         hints.ai_family = PF_UNSPEC;
30         hints.ai_socktype = SOCK_STREAM;
31         error = getaddrinfo(host, port, &hints, &res);
32         if (error||!res)
33                 perror_msg_and_die(gai_strerror(error));
34         addr_info=res;
35         while (res) {
36                 s=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
37                 if (s<0)
38                 {
39                         error=s;
40                         res=res->ai_next;
41                         continue;
42                 }
43                 /* try to connect() to res->ai_addr */
44                 error = connect(s, res->ai_addr, res->ai_addrlen);
45                 if (error >= 0)
46                         break;
47                 close(s);
48                 res=res->ai_next;
49         }
50         freeaddrinfo(addr_info);
51         if (error < 0)
52         {
53                 perror_msg_and_die("Unable to connect to remote host (%s)", host);
54         }
55         return s;
56 #else
57         struct sockaddr_in s_addr;
58         int s = socket(AF_INET, SOCK_STREAM, 0);
59         struct servent *tserv;
60         int port_nr=atoi(port);
61         struct hostent * he;
62
63         if (port_nr==0 && (tserv = getservbyname(port, "tcp")) != NULL)
64                 port_nr = tserv->s_port;
65
66         memset(&s_addr, 0, sizeof(struct sockaddr_in));
67         s_addr.sin_family = AF_INET;
68         s_addr.sin_port = htons(port_nr);
69
70         he = xgethostbyname(host);
71         memcpy(&s_addr.sin_addr, he->h_addr, sizeof s_addr.sin_addr);
72
73         if (connect(s, (struct sockaddr *)&s_addr, sizeof s_addr) < 0)
74         {
75                 perror_msg_and_die("Unable to connect to remote host (%s)", host);
76         }
77         return s;
78 #endif
79 }