SUCKUP.de

Kurztipp: lokalen offenen Port finden (bash)

Konsolen-Logo

Konsolen-Logo

This blog post has been published on 2014-06-21 and may be out of date.

Habe soeben folgende Funktionen zu meinen dotfiles hinzugefügt, um einen freien lokalen Port zu finden. Diese werden wiederum verwendet, um z.B. die “phpserver“-Funktion auszuführen.

# -------------------------------------------------------------------
# netstat_used_local_ports: get used tcp-ports
netstat_used_local_ports()
{
  netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$' | sort -n | uniq
}

# -------------------------------------------------------------------
# netstat_free_local_port: get one free tcp-port
netstat_free_local_port()
{
  read lowerPort upperPort < /proc/sys/net/ipv4/ip_local_port_range
 
  # create a local array of used ports 
  local all_used_ports=($(netstat_used_local_ports))

  for port in $(seq $lowerPort $upperPort); do
    for used_port in "${all_used_ports[@]}"; do
      if [ $used_port -eq $port ]; then
        continue
      else
        echo $port
        return 0
      fi
    done
  done 
}