zrok/util/autoListener.go

30 lines
686 B
Go
Raw Normal View History

2024-11-07 18:57:11 +01:00
package util
2024-11-06 23:18:20 +01:00
import (
"fmt"
"net"
)
func AutoListener(protocol, address string, startPort, endPort uint16) (net.Listener, error) {
2024-11-06 23:18:20 +01:00
for i := startPort; i <= endPort; i++ {
l, err := net.Listen(protocol, fmt.Sprintf("%s:%d", address, i))
2024-11-06 23:18:20 +01:00
if err != nil {
continue
}
return l, nil
}
return nil, fmt.Errorf("no listener found in range")
}
func AutoListenerAddress(protocol, address string, startPort, endPort uint16) (string, error) {
listener, err := AutoListener(protocol, address, startPort, endPort)
if err != nil {
return "", err
}
autoAddress := listener.Addr().String()
if err := listener.Close(); err != nil {
return "", err
}
return autoAddress, nil
}