1 /* 2 ** 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 17 #include <errno.h> 18 #include <stddef.h> 19 #include <stdlib.h> 20 #include <string.h> 21 #include <unistd.h> 22 23 #include <sys/socket.h> 24 #include <sys/select.h> 25 #include <sys/types.h> 26 #include <netinet/in.h> 27 28 #include <cutils/sockets.h> 29 30 #define LISTEN_BACKLOG 4 31 32 /* open listen() port on any interface */ 33 int socket_inaddr_any_server(int port, int type) 34 { 35 struct sockaddr_in6 addr; 36 int s, n; 37 38 memset(&addr, 0, sizeof(addr)); 39 addr.sin6_family = AF_INET6; 40 addr.sin6_port = htons(port); 41 addr.sin6_addr = in6addr_any; 42 43 s = socket(AF_INET6, type, 0); 44 if (s < 0) return -1; 45 46 n = 1; 47 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n)); 48 49 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) { 50 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 } 67