Skip to content

Commit b9cc0b5

Browse files
committed
Show a better error when the port is in use
1 parent e6362a7 commit b9cc0b5

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

Command/ServerRunCommand.php

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,16 +95,29 @@ protected function execute(InputInterface $input, OutputInterface $output)
9595
}
9696

9797
$env = $this->getContainer()->getParameter('kernel.environment');
98+
$address = $input->getArgument('address');
99+
100+
if (false === strpos($address, ':')) {
101+
$output->writeln('The address has to be of the form <comment>bind-address:port</comment>.');
102+
103+
return 1;
104+
}
105+
106+
if ($this->isOtherServerProcessRunning($address)) {
107+
$output->writeln(sprintf('<error>A process is already listening on http://%s.</error>', $address));
108+
109+
return 1;
110+
}
98111

99112
if ('prod' === $env) {
100113
$output->writeln('<error>Running PHP built-in server in production environment is NOT recommended!</error>');
101114
}
102115

103-
if (null === $builder = $this->createPhpProcessBuilder($input, $output, $env)) {
116+
if (null === $builder = $this->createPhpProcessBuilder($output, $address, $input->getOption('router'), $env)) {
104117
return 1;
105118
}
106119

107-
$output->writeln(sprintf("Server running on <info>http://%s</info>\n", $input->getArgument('address')));
120+
$output->writeln(sprintf("Server running on <info>http://%s</info>\n", $address));
108121
$output->writeln('Quit the server with CONTROL-C.');
109122

110123
$builder->setWorkingDirectory($documentRoot);
@@ -127,9 +140,24 @@ protected function execute(InputInterface $input, OutputInterface $output)
127140
return $process->getExitCode();
128141
}
129142

130-
private function createPhpProcessBuilder(InputInterface $input, OutputInterface $output, $env)
143+
private function isOtherServerProcessRunning($address)
144+
{
145+
list($hostname, $port) = explode(':', $address);
146+
147+
$fp = @fsockopen($hostname, $port, $errno, $errstr, 5);
148+
149+
if (false !== $fp) {
150+
fclose($fp);
151+
152+
return true;
153+
}
154+
155+
return false;
156+
}
157+
158+
private function createPhpProcessBuilder(OutputInterface $output, $address, $router, $env)
131159
{
132-
$router = $input->getOption('router') ?: $this
160+
$router = $router ?: $this
133161
->getContainer()
134162
->get('kernel')
135163
->locateResource(sprintf('@FrameworkBundle/Resources/config/router_%s.php', $env))
@@ -150,6 +178,6 @@ private function createPhpProcessBuilder(InputInterface $input, OutputInterface
150178
return;
151179
}
152180

153-
return new ProcessBuilder(array($binary, '-S', $input->getArgument('address'), $router));
181+
return new ProcessBuilder(array($binary, '-S', $address, $router));
154182
}
155183
}

0 commit comments

Comments
 (0)