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#ifndef HAVE_WINSOCK
24#include <sys/socket.h>
25#include <sys/select.h>
26#include <sys/types.h>
27#include <netinet/in.h>
28#endif
29
30#include <cutils/sockets.h>
31
32/* Connect to port on the loopback IP interface. type is
33 * SOCK_STREAM or SOCK_DGRAM.
34 * return is a file descriptor or -1 on error
35 */
36int socket_loopback_client(int port, int type)
37{
38    struct sockaddr_in addr;
39    int s;
40
41    memset(&addr, 0, sizeof(addr));
42    addr.sin_family = AF_INET;
43    addr.sin_port = htons(port);
44    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
45
46    s = socket(AF_INET, type, 0);
47    if(s < 0) return -1;
48
49    if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
50        close(s);
51        return -1;
52    }
53
54    return s;
55
56}
57
58