Last active
December 7, 2016 17:09
-
-
Save damc-dev/c9fda009e6469392f9fc644bfdb50003 to your computer and use it in GitHub Desktop.
Find Free Ports - Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Source: http://unix.stackexchange.com/questions/55913/whats-the-easiest-way-to-find-an-unused-local-port#comment271991_132524 | |
# One liner: python -c 'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()' | |
import socket | |
s=socket.socket() | |
s.bind(("", 0)) | |
print(s.getsockname()[1]) | |
s.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
function isPortFree() { | |
PORT_FREE=`/usr/sbin/lsof -i:$1 | grep "LISTEN"` | |
if [ "X$PORT_FREE" = "X" ] | |
then | |
echo "1" | |
else | |
echo "0" | |
fi | |
} | |
function findFreeport() { | |
# finds a range of port numbers with ip_local_port_range | |
read lowerPort upperPort < /proc/sys/net/ipv4/ip_local_port_range | |
range=$(($upperPort - $lowerPort)) | |
IS_PORT_FREE=0 | |
# generate a random open port in the range | |
while [ X"$IS_PORT_FREE" == "X0" ]; do | |
random_port=`echo $(($lowerPort+$RANDOM % $range))` | |
IS_PORT_FREE=`isPortFree $random_port` | |
done | |
echo $random_port | |
} | |
FREE_PORT=`findFreeport` | |
echo "$FREE_PORT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment