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 #define LISTEN_BACKLOG 4
24
25 #if !defined(_WIN32)
26 #include <sys/socket.h>
27 #include <sys/select.h>
28 #include <sys/types.h>
29 #include <netinet/in.h>
30 #endif
31
32 #include <cutils/sockets.h>
33
34 /* open listen() port on loopback interface */
socket_loopback_server(int port,int type)35 int socket_loopback_server(int port, int type)
36 {
37 struct sockaddr_in addr;
38 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_LOOPBACK);
44
45 s = socket(AF_INET, type, 0);
46 if(s < 0) return -1;
47
48 n = 1;
49 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n));
50
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 }
69
70