1 /* libs/cutils/socket_inaddr_any_server.c 2 ** 3 ** Copyright 2006, The Android Open Source Project 4 ** 5 ** Licensed under the Apache License, Version 2.0 (the "License"); 6 ** you may not use this file except in compliance with the License. 7 ** You may obtain a copy of the License at 8 ** 9 ** http://www.apache.org/licenses/LICENSE-2.0 10 ** 11 ** Unless required by applicable law or agreed to in writing, software 12 ** distributed under the License is distributed on an "AS IS" BASIS, 13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 ** See the License for the specific language governing permissions and 15 ** limitations under the License. 16 */ 17 18 #include <cutils/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 size_t alen; 40 int s, n; 41 42 memset(&addr, 0, sizeof(addr)); 43 addr.sin_family = AF_INET; 44 addr.sin_port = htons(port); 45 addr.sin_addr.s_addr = htonl(INADDR_ANY); 46 47 s = socket(AF_INET, type, 0); 48 if(s < 0) return -1; 49 50 n = 1; 51 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)); 52 53 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) { 54 close(s); 55 return -1; 56 } 57 58 if (type == SOCK_STREAM) { 59 int ret; 60 61 ret = listen(s, LISTEN_BACKLOG); 62 63 if (ret < 0) { 64 close(s); 65 return -1; 66 } 67 } 68 69 return s; 70 } 71