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