Skip to content

Commit 26265f0

Browse files
committed
Use random available port rather than randomly generated one
1 parent 1da1cf9 commit 26265f0

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/ChromeDevtoolsProtocol/Instance/Launcher.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,11 @@ class Launcher
4040
private $input;
4141

4242
/**
43-
* @param int $port If port <= 0, random port number is generated.
44-
* @throws \Exception
43+
* @param int $port If port <= 0, random available port is used.
4544
*/
4645
public function __construct($port = 0)
4746
{
48-
if ($port <= 0) {
49-
$port = random_int(1024 + 1, 65535);
50-
}
51-
52-
$this->port = $port;
47+
$this->port = max(0, $port);
5348
}
5449

5550
/**
@@ -212,6 +207,10 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
212207
$temporaryUserDataDir = null;
213208
if (!$foundUserDataDir) {
214209
$temporaryUserDataDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "chrome-profile-" . $this->port;
210+
if ($this->port === 0) {
211+
$temporaryUserDataDir .= "-" . bin2hex(random_bytes(8));
212+
}
213+
215214
$fs->mkdir($temporaryUserDataDir);
216215
$args[] = "--user-data-dir=" . $temporaryUserDataDir;
217216
}
@@ -226,6 +225,16 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
226225
);
227226
$process->start();
228227

228+
if ($this->port === 0) {
229+
$process->waitUntil(function ($type, $buffer) {
230+
if (preg_match('~DevTools listening on ws://.+:(\d+)/devtools~', $buffer, $m)) {
231+
$this->port = (int)$m[1];
232+
return true;
233+
}
234+
return false;
235+
});
236+
}
237+
229238
$instance = new ProcessInstance($process, $temporaryUserDataDir, $this->port);
230239

231240
for (; ;) {

0 commit comments

Comments
 (0)