Skip to content

Instantly share code, notes, and snippets.

@jwangac
Created December 28, 2023 10:00
Show Gist options
  • Select an option

  • Save jwangac/25f4e2f630bc9bc2cf5f2c1c45c39db0 to your computer and use it in GitHub Desktop.

Select an option

Save jwangac/25f4e2f630bc9bc2cf5f2c1c45c39db0 to your computer and use it in GitHub Desktop.

Revisions

  1. jwangac created this gist Dec 28, 2023.
    33 changes: 33 additions & 0 deletions adb-network-connect
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    #!/bin/bash
    set -euo pipefail
    shopt -s inherit_errexit

    if [[ $# -ne 1 ]]; then
    >&2 echo "usage: $0 <hostname>"
    exit 1
    fi

    # fix freeze when adb is not running
    adb start-server >/dev/null 2>/dev/null
    sleep 0.1

    devices=$(adb devices | grep -v "List" | grep device | wc -l || true)
    if [[ $devices -gt 0 ]]; then
    echo "Devices are connected."
    adb disconnect
    fi

    hostname="$1"
    ipv4=$(dig +short "$hostname" A | head -n 1)

    port="$(nmap $ipv4 -p 37000-44000 | awk "/\/tcp/" | cut -d/ -f1 | sort | head -n 1)"
    target="$ipv4:$port"

    echo "Target: $target"
    adb connect "$target"
    if [[ "$port" != "37000" ]]; then
    adb tcpip 37000
    adb disconnect
    sleep 1
    adb connect "$ipv4:37000"
    fi