Tizen 2.1 base
[sdk/target/sdbd.git] / src / socket_inaddr_any_server.c
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 // libs/cutils/socket_inaddr_any_server.c
17
18 #include "sockets.h"
19
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <stddef.h>
25
26 #ifndef HAVE_WINSOCK
27 #include <sys/socket.h>
28 #include <sys/select.h>
29 #include <sys/types.h>
30 #include <netinet/in.h>
31 #endif
32
33 #define LISTEN_BACKLOG 4
34
35 /* open listen() port on any interface */
36 int socket_inaddr_any_server(int port, int type)
37 {
38     struct sockaddr_in addr;
39     int s, n;
40
41     memset(&addr, 0, sizeof(addr));
42     addr.sin_family = AF_INET;
43     addr.sin_port = htons(port);
44     addr.sin_addr.s_addr = htonl(INADDR_ANY);
45
46     s = socket(AF_INET, type, 0);
47     if(s < 0) return -1;
48
49     n = 1;
50     if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) < 0) {
51         close(s);
52         return -1;
53     }
54
55     if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
56         close(s);
57         return -1;
58     }
59
60     if (type == SOCK_STREAM) {
61         int ret;
62
63         ret = listen(s, LISTEN_BACKLOG);
64
65         if (ret < 0) {
66             close(s);
67             return -1; 
68         }
69     }
70
71     return s;
72 }