Mark Salyzyn | 1271716 | 2014-04-29 15:49:14 -0700 | [diff] [blame] | 1 | /* |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 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 | |
Mark Salyzyn | 1271716 | 2014-04-29 15:49:14 -0700 | [diff] [blame] | 17 | #include <errno.h> |
| 18 | #include <stddef.h> |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 19 | #include <stdlib.h> |
| 20 | #include <string.h> |
| 21 | #include <unistd.h> |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 22 | |
Elliott Hughes | adbf442 | 2015-07-29 17:45:24 -0700 | [diff] [blame] | 23 | #if !defined(_WIN32) |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 24 | #include <sys/socket.h> |
| 25 | #include <sys/select.h> |
| 26 | #include <sys/types.h> |
| 27 | #include <netinet/in.h> |
| 28 | #endif |
| 29 | |
Mark Salyzyn | 1271716 | 2014-04-29 15:49:14 -0700 | [diff] [blame] | 30 | #include <cutils/sockets.h> |
| 31 | |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 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 | */ |
| 36 | int socket_loopback_client(int port, int type) |
| 37 | { |
| 38 | struct sockaddr_in addr; |
The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 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 | |