blob: 6c849de771d62ca2e23ee1ebf51d2adf5c5d2a25 [file] [log] [blame]
Mark Salyzyn12717162014-04-29 15:49:14 -07001/*
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002** Copyright 2006, The Android Open Source Project
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
Mark Salyzyn12717162014-04-29 15:49:14 -070017#include <errno.h>
18#include <stddef.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include <stdlib.h>
20#include <string.h>
21#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080022
23#ifndef HAVE_WINSOCK
24#include <sys/socket.h>
25#include <sys/select.h>
26#include <sys/types.h>
27#include <netinet/in.h>
28#endif
29
Mark Salyzyn12717162014-04-29 15:49:14 -070030#include <cutils/sockets.h>
31
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080032#define LISTEN_BACKLOG 4
33
34/* open listen() port on any interface */
35int socket_inaddr_any_server(int port, int type)
36{
37 struct sockaddr_in addr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080038 int s, n;
39
40 memset(&addr, 0, sizeof(addr));
41 addr.sin_family = AF_INET;
42 addr.sin_port = htons(port);
43 addr.sin_addr.s_addr = htonl(INADDR_ANY);
44
45 s = socket(AF_INET, type, 0);
46 if(s < 0) return -1;
47
48 n = 1;
Mark Salyzyn02a7c3a2014-05-05 08:49:13 -070049 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080050
51 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
52 close(s);
53 return -1;
54 }
55
56 if (type == SOCK_STREAM) {
57 int ret;
58
59 ret = listen(s, LISTEN_BACKLOG);
60
61 if (ret < 0) {
62 close(s);
63 return -1;
64 }
65 }
66
67 return s;
68}