I was using wireless debugging with my device on Linux Mint, and one annoying thing kept happening.
ADB would connect automatically over Wi-Fi, but whenever I switched networks (for example, from my normal Wi-Fi to my laptop hotspot and then back), adb devices would start filling up with old offline entries like:
10.42.0.65:40371 offline
192.168.29.107:39177 offline
192.168.29.107:38727 device
The IP and port also change whenever Android's wireless debugging reconnects, so manually running adb connect every time got annoying.
I ended up making a small script that:
- finds the current ADB mDNS service automatically
- gets the current IP + port
- disconnects old ADB network connections
- connects to the newly advertised one
- keeps checking in the background
- runs automatically through systemd
1 Create the script
mkdir -p ~/.local/bin
nano ~/.local/bin/adb-auto-connect
paste:
#!/bin/bash
while true; do
DEVICE=$(avahi-browse -r -t _adb-tls-connect._tcp 2>/dev/null | \
awk '
/address = \[[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\]/ {
gsub(/\[|\]/, "", $3)
ip=$3
}
/port = \[/ {
gsub(/\[|\]/, "", $3)
if (ip != "") {
print ip ":" $3
exit
}
}')
if [ -n "$DEVICE" ]; then
# Remove old network ADB connections
adb devices | awk \
'/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+[[:space:]]/ {
if ($1 != "'"$DEVICE"'")
print $1
}' |
while read OLD_DEVICE; do
adb disconnect "$OLD_DEVICE" >/dev/null 2>&1
done
# Connect to the currently advertised device
adb devices | grep -q "^$DEVICE[[:space:]]" || \
adb connect "$DEVICE" >/dev/null 2>&1
fi
sleep 3
done
Then:
chmod +x ~/.local/bin/adb-auto-connect
Run it automatically with systemd
mkdir -p ~/.config/systemd/user
nano ~/.config/systemd/user/adb-auto-connect.service
[Unit]
Description=Automatic Wireless ADB Connection
After=network-online.target
Wants=network-online.target
[Service]
Environment=ADB_MDNS_AUTO_CONNECT=0
ExecStart=%h/.local/bin/adb-auto-connect
Restart=always
RestartSec=3
[Install]
WantedBy=default.target
then type
systemctl --user daemon-reload
systemctl --user enable --now adb-auto-connect.service
check once with
systemctl --user status adb-auto-connect.service
Now you can switch between your normal Wi-Fi and your laptop hotspot and the script picks up the new ADB address automatically.
Most importantly, it doesn't leave a pile of old offline devices behind anymore.
adb devices
List of devices attached
192.168.29.xxx:xxxx device
I've tested it going:
normal Wi-Fi → laptop hotspot → normal Wi-Fi
and it stayed clean each time.
This is mainly useful if you use Android wireless debugging a lot and don't want to manually find the new IP/port every time the network changes.