1. 程式人生 > >shell 獲得本機IP和free埠

shell 獲得本機IP和free埠

#!/bin/bash
IPaddr=`ifconfig | grep inet\\\\s | grep -v "127.0.0." | sed "s/addr://g"| awk '{print $2}'`
function getfreeport()
{
    IPaddr=$1
    first=$2
    last=$3
    for (( port = $first; port <= ${last}; port++ ))
        do
            (echo > /dev/tcp/$IPaddr/$port) &> /dev/null
            if [ $? != 0 ]
            then
                 echo $port
                 break
            fi
        done
}
port=$(getfreeport $IPaddr 22 100)
echo "free port=${port}"