2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.dumprendertree2.forwarder;
19 import android.util.Log;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.net.Socket;
27 * The utility class that can setup a socket allowing the device to communicate with remote
28 * machines through the machine that the device is connected to via adb.
30 public class AdbUtils {
31 private static final String LOG_TAG = "AdbUtils";
33 private static final String ADB_OK = "OKAY";
34 private static final int ADB_PORT = 5037;
35 private static final String ADB_HOST = "127.0.0.1";
36 private static final int ADB_RESPONSE_SIZE = 4;
39 * Creates a new socket that can be configured to serve as a transparent proxy to a
40 * remote machine. This can be achieved by calling configureSocket()
42 * @return a socket that can be configured to link to remote machine
45 public static Socket createSocket() throws IOException{
46 return new Socket(ADB_HOST, ADB_PORT);
50 * Configures the connection to serve as a transparent proxy to a remote machine.
51 * The given streams must belong to a socket created by createSocket().
53 * @param inputStream inputStream of the socket we want to configure
54 * @param outputStream outputStream of the socket we want to configure
55 * @param remoteAddress address of the remote machine (as you would type in a browser
56 * in a machine that the device is connected to via adb)
57 * @param remotePort port on which to connect
58 * @return if the configuration suceeded
61 public static boolean configureConnection(InputStream inputStream, OutputStream outputStream,
62 String remoteAddress, int remotePort) throws IOException {
63 String cmd = "tcp:" + remotePort + ":" + remoteAddress;
64 cmd = String.format("%04X", cmd.length()) + cmd;
66 byte[] buf = new byte[ADB_RESPONSE_SIZE];
67 outputStream.write(cmd.getBytes());
68 int read = inputStream.read(buf);
69 if (read != ADB_RESPONSE_SIZE || !ADB_OK.equals(new String(buf))) {
70 Log.w(LOG_TAG, "adb cmd failed.");