Home | History | Annotate | Download | only in libcutils
      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 <cutils/sockets.h>
     18 
     19 #include <errno.h>
     20 #include <stddef.h>
     21 #include <stdlib.h>
     22 #include <string.h>
     23 #include <unistd.h>
     24 
     25 #include <sys/socket.h>
     26 #include <sys/select.h>
     27 #include <sys/types.h>
     28 #include <netinet/in.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