ADB over TCP inside WSL2

2021-12-11 ยท 2 min read

    Problem #

    There are two problems with WSL2 that make connecting to an Android device over adb challenging. First, the network interface inside WSL2 is behind a NAT and not exposed to the LAN. This means we can't directly connect to any devices (like our phone) on the LAN. Second, any connected USB devices aren't visible inside WSL2.

    Possible Approaches #

    1. (Chosen) Create a socat tunnel inside Windows pointing at the phone.

    2. Change the WSL2 virtual network from NAT to Bridge mode (looks sketchy)

      https://develmonk.com/2021/06/05/easiest-wsl2-bridge-network-without-hyper-v-virtual-network-manager/

    3. Hack some stuff to make USB devices forward to WSL2? (looks sketchy)

      https://devblogs.microsoft.com/commandline/connecting-usb-devices-to-wsl/

    Overview #

    Since we can't connect directly from WSL2 to our device, we're going to set up a TCP tunnel running on the Windows side, pointing to the device. We'll then run all our adb operations over this tunnel.

    Process #

    1. Install socat inside MSYS2 in Windows.

      msys$ pacman -S socat
      
    2. On the Android device, enable "Wireless debugging" inside the Developer options.

    3. In the "Wireless debugging" menu, hit "Pair device with pairing code". This will generate a random code and bind the phone adb daemon to a random port. This port is only used temporarily for the pairing process.

    4. Inside MSYS2, setup a temporary tunnel pointing to the device IP and port for the WSL2 adb to pair on.

      msys$ socat tcp4-listen:2205,reuseaddr,fork,nodelay tcp4-connect:192.168.2.242:43148,nodelay
      
    5. Inside WSL2, pair with the android device over our temporary socat tunnel.

      wsl2$ ifconfig
      eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
          inet 172.19.160.252  netmask 255.255.240.0  broadcast 172.19.175.255
      
      wsl2$ adb pair 172.19.160.1:2205
      
    6. Close the temporary socat tunnel.

    7. Note the long-term wireless debugging port, in this case 38654.

    8. Inside MSYS2, setup a new tunnel pointing at the device IP and long-term port. Keep in mind that we'll always need this tunnel running whenever we want to use adb inside WSL2.

      msys$ socat tcp4-listen:2205,reuseaddr,fork,nodelay tcp4-connect:192.168.2.242:38654,nodelay
      
    9. Inside WSL2, connect to the android device over our tunnel.

      wsl2$ adb connect 172.19.160.1.:2205
      
    10. Make sure it works.

      wsl2$ adb shell
      walleye:/ $