2024-11-07 18:57:11 +01:00
|
|
|
package util
|
2024-11-06 23:18:20 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
2024-11-07 19:36:09 +01:00
|
|
|
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++ {
|
2024-11-07 19:36:09 +01:00
|
|
|
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")
|
|
|
|
}
|
2024-11-07 19:36:09 +01:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|