fd1820101bc3c6fa32343c59425a8947bff94ef4
[cascardo/rnetproxy.git] / tcp_server.c
1 /*
2  * Copyright (C) 2008-2009  Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
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_server (struct addrinfo *ai)
29 {
30   int fd;
31   int optval = 1;
32   fd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
33   if (fd < 0)
34     return -1;
35   setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (int));
36   if (bind (fd, ai->ai_addr, ai->ai_addrlen) < 0)
37     {
38       close (fd);
39       return -1;
40     }
41   if (listen (fd, 5) < 0)
42     {
43       close (fd);
44       return -1;
45     }
46   return fd;
47 }
48
49 static int
50 tcp_server_list (struct addrinfo *ai)
51 {
52   int fd = -1;
53   for (; ai; ai = ai->ai_next)
54     {
55       fd = tcp_server (ai);
56       if (fd >= 0)
57         {
58           return fd;
59         }
60     }
61   return fd;
62 }
63
64 int
65 hc_tcp_server (char *service)
66 {
67   struct addrinfo hint;
68   struct addrinfo *ai = NULL;
69   int fd;
70   hint.ai_family = AF_UNSPEC;
71   hint.ai_socktype = SOCK_STREAM;
72   hint.ai_protocol = 0;
73   hint.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_V4MAPPED;
74   if (getaddrinfo (NULL, service, &hint, &ai) < 0)
75     return -1;
76   fd = tcp_server_list (ai);
77   freeaddrinfo (ai);
78   return fd;
79 }
80
81 #ifdef TEST
82 int
83 main (int argc, char **argv)
84 {
85   char *service;
86   int fd;
87   service = (argc >= 2) ? argv[1] : "110";
88   fd = hc_tcp_server (service);
89   if (fd > 0)
90     close (fd);
91   return 0;
92 }
93 #endif