Compila rnetserver e rnetclient.
[cascardo/rnetproxy.git] / tcp_connect.c
1 /*
2  * Copyright (C) 2008-2009  Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  *
17  */
18
19 #include <sys/socket.h>
20 #include <sys/types.h>
21 #include <netinet/in.h>
22 #include <netdb.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 static int
28 tcp_connect (struct addrinfo *ai)
29 {
30   int fd;
31   fd = socket (ai->ai_family, SOCK_STREAM, 0);
32   if (fd < 0)
33     return -1;
34   if (connect (fd, ai->ai_addr, ai->ai_addrlen) < 0)
35     {
36       close (fd);
37       return -1;
38     }
39   return fd;
40 }
41
42 static int
43 tcp_connect_list (struct addrinfo *ai)
44 {
45   int fd = -1;
46   for (; ai; ai = ai->ai_next)
47     {
48       fd = tcp_connect (ai);
49       if (fd >= 0)
50         {
51           return fd;
52         }
53     }
54   return fd;
55 }
56
57 int
58 hc_tcp_connect (char *server, char *service)
59 {
60   struct addrinfo *ai = NULL;
61   int fd;
62   if (getaddrinfo (server, service, NULL, &ai) < 0)
63     return -1;
64   fd = tcp_connect_list (ai);
65   freeaddrinfo (ai);
66   return fd;
67 }
68
69 #ifdef TEST
70 int
71 main (int argc, char **argv)
72 {
73   char *server;
74   char *service;
75   int fd;
76   server = (argc >= 2) ? argv[1] : "localhost";
77   service = (argc >= 3) ? argv[2] : "110";
78   fd = hc_tcp_connect (server, service);
79   if (fd > 0)
80     close (fd);
81   return 0;
82 }
83 #endif