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
34static int _socket_loopback_server(int family, int type, struct sockaddr * addr, size_t size)
35{
36    int s, n;
37
38    s = socket(family, type, 0);
39    if(s < 0)
40        return -1;
41
42    n = 1;
43    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n));
44
45    if(bind(s, addr, size) < 0) {
46        close(s);
47        return -1;
48    }
49
50    if (type == SOCK_STREAM) {
51        int ret;
52
53        ret = listen(s, LISTEN_BACKLOG);
54
55        if (ret < 0) {
56            close(s);
57            return -1;
58        }
59    }
60
61    return s;
62}
63
64/* open listen() port on loopback IPv6 interface */
65int socket_loopback_server6(int port, int type)
66{
67    struct sockaddr_in6 addr;
68
69    memset(&addr, 0, sizeof(addr));
70    addr.sin6_family = AF_INET6;
71    addr.sin6_port = htons(port);
72    addr.sin6_addr = in6addr_loopback;
73
74    return _socket_loopback_server(AF_INET6, type, (struct sockaddr *) &addr, sizeof(addr));
75}
76
77/* open listen() port on loopback interface */
78int socket_loopback_server(int port, int type)
79{
80    struct sockaddr_in addr;
81
82    memset(&addr, 0, sizeof(addr));
83    addr.sin_family = AF_INET;
84    addr.sin_port = htons(port);
85    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
86
87    return _socket_loopback_server(AF_INET, type, (struct sockaddr *) &addr, sizeof(addr));
88}
89