blob: 27c5333f3ab949f2cd9ea5d5cadef2a8471b7b2a [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
Elliott Hughes8e9aeb92017-11-10 10:22:07 -080017#include <cutils/sockets.h>
18
Mark Salyzyn12717162014-04-29 15:49:14 -070019#include <errno.h>
20#include <stddef.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080021#include <stdlib.h>
22#include <string.h>
23#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080024
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <sys/socket.h>
26#include <sys/select.h>
27#include <sys/types.h>
28#include <netinet/in.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080029
30#define LISTEN_BACKLOG 4
31
32/* open listen() port on any interface */
33int socket_inaddr_any_server(int port, int type)
34{
Erik Klinec40da922015-12-07 16:09:39 +090035 struct sockaddr_in6 addr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080036 int s, n;
37
38 memset(&addr, 0, sizeof(addr));
Erik Klinec40da922015-12-07 16:09:39 +090039 addr.sin6_family = AF_INET6;
40 addr.sin6_port = htons(port);
41 addr.sin6_addr = in6addr_any;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042
Erik Klinec40da922015-12-07 16:09:39 +090043 s = socket(AF_INET6, type, 0);
44 if (s < 0) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045
46 n = 1;
Mark Salyzyn02a7c3a2014-05-05 08:49:13 -070047 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080048
Erik Klinec40da922015-12-07 16:09:39 +090049 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080050 close(s);
51 return -1;
52 }
53
54 if (type == SOCK_STREAM) {
55 int ret;
56
57 ret = listen(s, LISTEN_BACKLOG);
58
59 if (ret < 0) {
60 close(s);
61 return -1;
62 }
63 }
64
65 return s;
66}