blob: 0d670f286ef0d3362b741bee30ef178006d198f8 [file] [log] [blame]
Eric Andersen0b315862002-07-03 11:51:44 +00001/* 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 <sys/types.h>
12#include <sys/socket.h>
13#include <netdb.h>
14#include <stdlib.h>
15#include "libbb.h"
16
17int xconnect(const char *host, const char *port)
18{
19#if CONFIG_FEATURE_IPV6
20 struct addrinfo hints;
21 struct addrinfo *res;
22 struct addrinfo *addr_info;
23 int error;
24 int s;
25
26 memset(&hints, 0, sizeof(hints));
27 /* set-up hints structure */
28 hints.ai_family = PF_UNSPEC;
29 hints.ai_socktype = SOCK_STREAM;
30 error = getaddrinfo(host, port, &hints, &res);
31 if (error||!res)
32 perror_msg_and_die(gai_strerror(error));
33 addr_info=res;
34 while (res) {
35 s=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
36 if (s<0)
37 {
38 error=s;
39 res=res->ai_next;
40 continue;
41 }
42 /* try to connect() to res->ai_addr */
43 error = connect(s, res->ai_addr, res->ai_addrlen);
44 if (error >= 0)
45 break;
46 close(s);
47 res=res->ai_next;
48 }
49 freeaddrinfo(addr_info);
50 if (error < 0)
51 {
52 perror_msg_and_die("Unable to connect to remote host (%s)", host);
53 }
54 return s;
55#else
56 struct sockaddr_in s_addr;
57 int s = socket(AF_INET, SOCK_STREAM, 0);
58 struct servent *tserv;
59 int port_nr=atoi(port);
60 struct hostent * he;
61
62 if (port_nr==0 && (tserv = getservbyname(port, "tcp")) != NULL)
63 port_nr = tserv->s_port;
64
65 memset(&s_addr, 0, sizeof(struct sockaddr_in));
66 s_addr.sin_family = AF_INET;
67 s_addr.sin_port = htons(port_nr);
68
69 he = xgethostbyname(host);
70 memcpy(&s_addr.sin_addr, he->h_addr, sizeof s_addr.sin_addr);
71
72 if (connect(s, (struct sockaddr *)&s_addr, sizeof s_addr) < 0)
73 {
74 perror_msg_and_die("Unable to connect to remote host (%s)", host);
75 }
76 return s;
77#endif
78}