I am currently working on improving my Jenkins Pipeline, which starts a docker container with an exposed port. But due to the fact, that the Jenkins instance is heavily used by many people and their projects, I have run into the problem, that the exposed port mapping is already in use.

My idea is to determine an unused port on the host machine, to circumvent this problem. In order to do this, I want to expand our Jenkins shared the library with a simple method to check and return the first unused port from the host system.

Has anyone an idea how to achieve this?

My current solution would be to utilize a shell function which somehow uses the netstat tool.

File: getRandomFreePort.groovy

```
def call() {
sh '''
    #!/bin/bash
    while
    [[!-z $CHECK]]; do
    PORT = $(((RANDOM % 60000) + 1025))
    CHECK = $(sudo netstat - ap | grep $PORT)
    done

    echo $PORT
'''
}

```