Replace ping sweep with direct parallel port scan across full subnet

Ping sweep + wait was the bottleneck: it blocked until all 254 pings
timed out before starting the port check. Now all 254 nc checks fire
simultaneously and we stop polling as soon as the first hit is written,
completing in ~1s instead of ~1 minute.
This commit is contained in:
cediackermann 2026-04-24 11:49:32 +02:00
parent 4564c637f4
commit 6e02572bd7

View file

@ -77,40 +77,25 @@ detect_ollama_host() {
local LOCAL_IP
LOCAL_IP=$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo "")
if [ -z "$LOCAL_IP" ]; then
echo "" >&2
print_warning "Could not determine local IP address." >&2
else
local SUBNET
SUBNET=$(echo "$LOCAL_IP" | cut -d. -f1-3)
# Ping-sweep the subnet in parallel to populate the ARP cache,
# then read ARP for live hosts and check port 11434 on all of them.
echo "" >&2
print_warning "Ping-sweeping ${SUBNET}.0/24 to find live devices..." >&2
for i in $(seq 1 254); do
ping -c1 -W1 "${SUBNET}.${i}" &>/dev/null &
done
wait
local ARP_IPS
ARP_IPS=$(arp -a 2>/dev/null | grep -v incomplete | grep -oE '\(([0-9]{1,3}\.){3}[0-9]{1,3}\)' | tr -d '()')
if [ -z "$ARP_IPS" ]; then
print_warning "No live devices found on ${SUBNET}.0/24." >&2
else
local COUNT
COUNT=$(echo "$ARP_IPS" | wc -l | tr -d ' ')
print_warning "Checking $COUNT live devices for Ollama (port 11434)..." >&2
print_warning "Scanning ${SUBNET}.0/24 for Ollama (port 11434)..." >&2
local TMPFILE
TMPFILE=$(mktemp)
while IFS= read -r ip; do
# Launch all 254 checks simultaneously
for i in $(seq 1 254); do
local ip="${SUBNET}.${i}"
echo -e " ${BLUE}${NC} Checking $ip..." >&2
( nc -z -w 1 "$ip" 11434 2>/dev/null && echo "$ip" >> "$TMPFILE" ) &
done <<< "$ARP_IPS"
done
# Stop as soon as the first result is written
# Poll every 200ms and stop as soon as the first result appears
while [ "$(jobs -rp | wc -l)" -gt 0 ]; do
if [ -s "$TMPFILE" ]; then
kill $(jobs -rp) 2>/dev/null || true
@ -141,8 +126,7 @@ detect_ollama_host() {
return
fi
print_warning "Ollama not found on any live device." >&2
fi
print_warning "Ollama not found on any device in ${SUBNET}.0/24." >&2
fi
# Nothing found — ask the user directly