Dima Zeuge
Dima Zeuge

Reputation: 99

What's the easiest way to find multiple unused local ports withing a range?

What I need is to find unused local ports withing a range for further usage (for appium nodes). I found this code:

getPorts() {
        freePort=$(netstat -aln | awk '
      $6 == "LISTEN" {
        if ($4 ~ "[.:][0-9]+$") {
          split($4, a, /[:.]/);
          port = a[length(a)];
          p[port] = 1
        }
      }
      END {
        for (i = 7777; i < 65000 && p[i]; i++){};
        if (i == 65000) {exit 1};
        print i
      }
    ')
    echo ${freePort}
}

this works pretty well if I need singe free port, but for parallel test execution we need multiple unused ports. So I need to modify the function to be able to get not one free port, but multiple (depends on parameter), starting from the first found free port and then store the result in one String variable. For example if I need ports for three 3 devices, the result should be: 7777 7778 7779

the code should work on macOS, because we're using mac mini as a test server.

Since I only started with bash, it's a bit complicated to do for me

Upvotes: 2

Views: 1696

Answers (2)

Xaqron
Xaqron

Reputation: 30877

Finding unused ports from 5000 to 5100:

range=(`seq 5000 5100`)
ports=`netstat -tuwan | awk '{print $4}' | grep ':' | cut -d ":" -f 2`
echo ${range[@]} ${ports[@]} ${ports[@]} | tr ' ' '\n' | sort | uniq -u

Upvotes: 0

Azize
Azize

Reputation: 4496

This is a bash code, it works fine on Linux, so if your Mac also runs bash it will work for you.

getPorts() {
    amount=${1}
    found=0
    ports=""
    for ((i=7777;i<=65000;i++))
    do
        (echo > /dev/tcp/127.0.0.1/${i}) >/dev/null 2>&1 || {
            #echo "${i}"
            ports="${ports} ${i}"
            found=$((found+1))
            if [[ ${found} -ge ${amount} ]]
            then
                echo "${ports:1}"
                return 0
            fi
        }
    done

    return 1
}

Here is how to use use it and the output:

$ getPorts 3
7777 7778 7779

$ getPorts 10
7777 7778 7779 7780 7781 7782 7783 7784 7785 7786

Upvotes: 1

Related Questions