My favorite way to do this is to run the following command ( replace PORT with the port number you want to check for ):
netstat -ln | grep :PORT
-l
= Show only listening ports
-n
= Show port number
If this command doesn't return anything, it shows that your PORT is available to use.In your script you can check $? to see the return code of the above command. If it's non-zero, the PORT is available.
One thing to note though is that, this doesn't tell you the status of your network e.g. if PORT is accessible from outside of your notwork.