Skip to content

Commit 242d8ec

Browse files
authored
Fix/reserve port (#114)
* Add playground session id * Fix reserve port
1 parent 49e3782 commit 242d8ec

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

internal/local_runner.go

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -347,17 +347,36 @@ func (d *LocalRunner) Stop() error {
347347
// reservePort finds the first available port from the startPort and reserves it
348348
// Note that we have to keep track of the port in 'reservedPorts' because
349349
// the port allocation happens before the services uses it and binds to it.
350-
func (d *LocalRunner) reservePort(startPort int) int {
350+
func (d *LocalRunner) reservePort(startPort int, protocol string) int {
351351
for i := startPort; i < startPort+1000; i++ {
352352
if _, ok := d.reservedPorts[i]; ok {
353353
continue
354354
}
355-
// make a net.Listen on the port to see if it is aavailable
356-
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", i))
357-
if err != nil {
358-
continue
355+
356+
bindAddr := "0.0.0.0"
357+
if d.bindHostPortsLocally {
358+
bindAddr = "127.0.0.1"
359359
}
360-
listener.Close()
360+
361+
if protocol == ProtocolUDP {
362+
listener, err := net.ListenUDP("udp", &net.UDPAddr{
363+
Port: i,
364+
IP: net.ParseIP(bindAddr),
365+
})
366+
if err != nil {
367+
continue
368+
}
369+
listener.Close()
370+
} else if protocol == ProtocolTCP {
371+
listener, err := net.Listen(protocol, fmt.Sprintf("%s:%d", bindAddr, i))
372+
if err != nil {
373+
continue
374+
}
375+
listener.Close()
376+
} else {
377+
panic(fmt.Sprintf("invalid protocol: %s", protocol))
378+
}
379+
361380
d.reservedPorts[i] = true
362381
return i
363382
}
@@ -642,7 +661,7 @@ func (d *LocalRunner) generateDockerCompose() ([]byte, error) {
642661
// between services running inside docker and the ones running on the host machine.
643662
for _, svc := range d.manifest.services {
644663
for _, port := range svc.ports {
645-
port.HostPort = d.reservePort(port.Port)
664+
port.HostPort = d.reservePort(port.Port, port.Protocol)
646665
}
647666
}
648667

0 commit comments

Comments
 (0)