searchPort Batchfile

What follows is some clever code for finding an available port number in Windows to start an instance of the selenium server. This is handy when you are trying to start multiple instances of selenium and need port numbers that are not in use. We created a Windows batch file named searchPort.bat as follows:

@echo OFF
set /A RAND=%RANDOM% %% 15000
set baseport=50000
set /a newPort=%RAND%+%basePort%
set freePort=
set startPort=%newPort%

:SEARCHPORT

netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL
if "%ERRORLEVEL%" equ "0" (
  set /a startPort +=1
  GOTO :SEARCHPORT
) ELSE (
  set freePort=%startPort%
  echo %startPort%
)

We randomize a number from 0 to 15,000, then add that number to 50,000. This number will be the startPort number. Ports 50,000 through 65,000 should be a safe port number ranger for Selenium. Once we have the rnadom start port number, we pass that into the SEARCHPORT routine to find if that port number is being used. If it is, we simply increment the startPort number by 1, and try again and again until we get a port that is available. Randomizing the starting port number will help to ensure that two instances of the selenium server trying to start at the same time do NOT start with the same port number. This will help to avoid port start collisions and reduce the possibility to a manageable frequency (like almost never).

To get a startPort number, we simply call that batch file in the startSelenium.bat (which starts our driver instance), as follows:

Setlocal EnableDelayedExpansion

SET TimeStamp=
FOR /f "tokens=1-4 delims=/ " %%i in ("%date%") do set datestr=%%l%%j%%k
FOR /f "tokens=1-4 delims=.: " %%i in ("%time%") do set timestr=%%i%%j%%k%%l
SET TimeStamp=%datestr%%timestr%
set a=%5
set b=0
set /a c=%a%+%b%

FOR /l %%t IN (1, 1, %c%) do (
  call c:\selenium\2\batchfiles\searchPort %startPort%
  echo !startPort!
  Start java -jar C:\Selenium\2\selenium-server-standalone-2.47.1.jar -port !startPort! -singleWindow -userExtensions C:\selenium\2\user-extensions.js -firefoxProfileTemplate "c:\selenium\2\ffprofiles\2rc" -htmlSuite "*chrome" "http://sv-selenium-t1/a=!startPort!j=%8b=%1c=%2d=%7e=%6f=%TimeStamp%g=%%..." "Z:\selenium\2\environment\%4\suites\%3" "u:\results\%4\result-%1-%computername%-!startPort!-%TimeStamp%.htm"
  timeout /t 10
)

Hope this helps someone else.

File: 

AttachmentSize
File searchPort.bat351 bytes
File startSelenium.bat821 bytes

Type: 

Batch