Skip to content

Commit 153a1ad

Browse files
Checking port availability
1 parent 3fc6650 commit 153a1ad

File tree

4 files changed

+25
-0
lines changed

4 files changed

+25
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"php": "^7.3 || ^8.0",
1616
"ext-curl": "*",
1717
"ext-json": "*",
18+
"ext-sockets": "*",
1819
"ext-zip": "*",
1920
"symfony/polyfill-mbstring": "^1.12",
2021
"symfony/process": "^5.0 || ^6.0 || ^7.0"

lib/Chrome/ChromeDriverService.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ public static function createDefaultService()
3838
if (!$port) {
3939
$port = static::DEFAULT_PORT;
4040
}
41+
self::checkPortIsAvail($port);
4142
$args = ['--port=' . $port];
4243

4344
return new static($pathToExecutable, $port, $args);

lib/Firefox/FirefoxDriverService.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ public static function createDefaultService()
3535
if (!$port) {
3636
$port = static::DEFAULT_PORT;
3737
}
38+
self::checkPortIsAvail($port);
3839
$args = ['-p=' . $port];
3940

4041
return new static($pathToExecutable, $port, $args);

lib/Remote/Service/DriverService.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,4 +180,26 @@ private function isExecutable(string $filename): bool
180180

181181
return false;
182182
}
183+
184+
/**
185+
* @param int $port
186+
* @throws RuntimeException
187+
*/
188+
protected static function checkPortIsAvail(int $port)
189+
{
190+
$errTest = function ($sock) use ($port) {
191+
if (!$sock) {
192+
$errCode = socket_last_error();
193+
$errMsg = $errCode ? socket_strerror($errCode) : 'Unknown';
194+
throw RuntimeException::forError("Port $port is not available: $errMsg");
195+
}
196+
};
197+
198+
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
199+
$errTest($sock);
200+
$errTest(socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1));
201+
$errTest(socket_bind($sock, '127.0.0.1', $port));
202+
$errTest(socket_listen($sock));
203+
socket_close($sock);
204+
}
183205
}

0 commit comments

Comments
 (0)