Konsolen-Logo

Kurztipp: lokalen offenen Port finden (bash)

closeThis post was published more than three months ago. Please note that the information offered here may no longer be current and valid. Therefore, please inform yourself about this topic elsewhere. If there is any new information, you can also send me a comment. Thank you so much!

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 
}

 

Published by

voku

Lars Moelleken | Ich bin root, ich darf das!