41

This is a query regarding the usage of adb on android.

Is there a way to forward the remote port i.e. port on the android device/emulator to the local machine to which the device is connected?

$ adb forward tcp:port1 tcp:port2 # forwards the local port port1 on the machine to port2 on the device.

Thanks in advance!

Gaurav Khurana
  • 411
  • 1
  • 4
  • 4
  • I'm in a similar situation right now, but I think I'll just going down the different route: Bind the app to 127.0.0.1:12345 and tunnel to that port. Why do you care so much who initiates the connection? Once you have a TCP connection established, both sides can talk/listen? – Benjamin Podszun Dec 29 '11 at 11:29

2 Answers2

33

Recently google updated ADB service. And added reverse command that should do the job.

From reverse documentation:

This implements the adb reverse feature, i.e. the ability to reverse socket connections from a device to the host. <forward-command> is one of the forwarding commands that are described above, as in:

  1. list-forward
  2. forward:<local>;<remote>
  3. forward:norebind:<local>;<remote>
  4. killforward-all
  5. killforward:<local>

Note that in this case, <local> corresponds to the socket on the device and <remote> corresponds to the socket on the host.

The output of reverse:list-forward is the same as host:list-forward except that <serial> will be just host.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
molokoka
  • 1,290
  • 12
  • 16
  • This answer is outdated and broken, but the feature still exists and works. The correct command structure is `adb reverse tcp:8888 tcp:9999` See `adb --help` for details! – Jessie Koffi May 27 '23 at 17:45
1

Do you truly need to forward the port or are you just looking for a way to communicate using sockets from a program running on the android shell to your host machine? I was able to accomplish the latter by sending my message to the port of interest on "10.0.2.2", which is the loopback adapter of the host machine. See docs here.

EDIT
This is the updated link

Akash Agarwal
  • 2,326
  • 1
  • 27
  • 57
RickNotFred
  • 3,381
  • 2
  • 24
  • 26
  • 25
    How would one accomplish this with a device rather than the emulator? – Johnny Jun 27 '11 at 08:50
  • 11
    @Johnny On a real device, you would use adb reverse. For instance, if you have a server on your host listening on port 8080 and you'd like to reverse-forward port 8000 on your device to it, you'd use `adb reverse tcp:8000 tcp:8080` – sacha Apr 01 '15 at 14:02
  • 1
    @sacha I cannot find any documentation on adb reverse command. Does it actually exist? What versions of SDK? – akuz Apr 27 '15 at 10:50
  • @akuz According to https://android.googlesource.com/platform/system/core/+/252586941934d23073a8d167ec240b221062505f, adb reverse was added to the android code in May 2014 – sacha May 03 '15 at 19:42