How can I find a free port with a batch file?
I tried to run a loop and using the netstat -o -n -a it will increment a variable until the port is not found in the netstat list
But I'm also not sure if this is the best way to find a free port.
set freePort=
set startPort=80
:SEARCHPORT
netstat -o -n -a | findstr ":%startPort%"
if %ERRORLEVEL% equ 0
( echo "port unavailable %ERRORLEVEL%"
set /a startPort +=1
GOTO :SEARCHPORT
) ELSE (
echo "port available %ERRORLEVEL%"
set freePort=%startPort%
GOTO :FOUNDPORT
)
:FOUNDPORT
echo free %freePort%
findstr ":%startPort%"
is not going to work because it also matches:8085
(which is open here) You should also clean up the code and insert some returns. (And use the code-button in the editor instead of>
)findstr ":%startPort%"
infindstr ":%startPort% "
, note the space after the last%
but you'll also get outgoing connections on:80
and I expect you only want to skip:80
for incoming. With-a
you also get all outgoing connections.