blob: 9aed7b7ce4bd84fe1d7951fbdc7594bcabdc9963 [file] [log] [blame]
Mark Salyzyn12717162014-04-29 15:49:14 -07001/*
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002** 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
Mark Salyzyn12717162014-04-29 15:49:14 -070017#include <errno.h>
18#include <stddef.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include <stdlib.h>
20#include <string.h>
21#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080022
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
Mark Salyzyn12717162014-04-29 15:49:14 -070030#include <cutils/sockets.h>
31
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080032/* 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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039 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