blob: f3a1b446209b9aaf3be15e19ef5a2fdacf7f92c8 [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>
Eric Andersencafc1032002-07-11 10:40:43 +000011#include <stdlib.h>
Eric Andersen0b315862002-07-03 11:51:44 +000012#include <sys/types.h>
13#include <sys/socket.h>
14#include <netdb.h>
Eric Andersencafc1032002-07-11 10:40:43 +000015#include <netinet/in.h>
Eric Andersen0b315862002-07-03 11:51:44 +000016#include "libbb.h"
17
18int 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;
Robert Grieblefd49832002-07-19 20:27:11 +000060 int port_nr=htons(atoi(port));
Eric Andersen0b315862002-07-03 11:51:44 +000061 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;
Robert Grieblefd49832002-07-19 20:27:11 +000068 s_addr.sin_port = port_nr;
Eric Andersen0b315862002-07-03 11:51:44 +000069
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}