AdbUtils.java revision 5af84db492a0c198377ba4dacc83c5a211e96ff6
1/* 2 * Copyright (C) 2010 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 17package com.android.dumprendertree2.forwarder; 18 19import android.util.Log; 20 21import java.io.IOException; 22import java.io.InputStream; 23import java.io.OutputStream; 24import java.net.Socket; 25 26/** 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. 29 */ 30public class AdbUtils { 31 private static final String LOG_TAG = "AdbUtils"; 32 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; 37 38 /** 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() 41 * 42 * @return a socket that can be configured to link to remote machine 43 */ 44 public static Socket createSocket() { 45 Socket socket = null; 46 try { 47 socket = new Socket(ADB_HOST, ADB_PORT); 48 } catch (IOException e) { 49 Log.e(LOG_TAG, "Creation failed.", e); 50 } 51 return socket; 52 } 53 54 /** 55 * Configures the connection to serve as a transparent proxy to a remote machine. 56 * The given streams must belong to a socket created by createSocket(). 57 * 58 * @param inputStream inputStream of the socket we want to configure 59 * @param outputStream outputStream of the socket we want to configure 60 * @param remoteAddress address of the remote machine (as you would type in a browser 61 * in a machine that the device is connected to via adb) 62 * @param remotePort port on which to connect 63 * @return if the configuration suceeded 64 * @throws IOException 65 */ 66 public static boolean configureConnection(InputStream inputStream, OutputStream outputStream, 67 String remoteAddress, int remotePort) throws IOException { 68 String cmd = "tcp:" + remotePort + ":" + remoteAddress; 69 cmd = String.format("%04X", cmd.length()) + cmd; 70 71 byte[] buf = new byte[ADB_RESPONSE_SIZE]; 72 outputStream.write(cmd.getBytes()); 73 int read = inputStream.read(buf); 74 if (read != ADB_RESPONSE_SIZE || !ADB_OK.equals(new String(buf))) { 75 Log.w(LOG_TAG, "adb cmd faild."); 76 return false; 77 } 78 return true; 79 } 80}