Skip to content

Commit 7ed9f55

Browse files
committed
Merge pull request #8 from clue/random-port
Automatically assign a random port for port 0
2 parents 19d5e14 + be5d1de commit 7ed9f55

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

Datagram/Factory.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,24 @@ protected function resolveAddress($address)
5454
if (strpos($address, '://') === false) {
5555
$address = 'udp://' . $address;
5656
}
57+
58+
// parse_url() does not accept null ports (random port assignment) => manually remove
59+
$nullport = false;
60+
if (substr($address, -2) === ':0') {
61+
$address = substr($address, 0, -2);
62+
$nullport = true;
63+
}
64+
5765
$parts = parse_url($address);
5866

5967
if (!$parts || !isset($parts['host'])) {
6068
return When::resolve($address);
6169
}
6270

71+
if ($nullport) {
72+
$parts['port'] = 0;
73+
}
74+
6375
// remove square brackets for IPv6 addresses
6476
$host = trim($parts['host'], '[]');
6577

tests/FactoryTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,16 @@ public function testCreateServer()
5353

5454
$capturedServer->close();
5555
}
56+
57+
public function testCreateServerRandomPort()
58+
{
59+
$promise = $this->factory->createServer('127.0.0.1:0');
60+
61+
$capturedServer = $this->getValueFromResolvedPromise($promise);
62+
$this->assertInstanceOf('Datagram\Socket', $capturedServer);
63+
64+
$this->assertNotEquals('127.0.0.1:0', $capturedServer->getLocalAddress());
65+
66+
$capturedServer->close();
67+
}
5668
}

0 commit comments

Comments
 (0)