Replace Dial with ListenUDP, add unit test

This commit is contained in:
iBug 2023-01-12 14:53:10 +08:00
parent 4879fff292
commit fefef3c43b
2 changed files with 27 additions and 8 deletions

View File

@ -489,19 +489,17 @@ func parseConfigBindAddress(ipstr string) (net.IP, error) {
} }
func testIPBindable(ip net.IP) error { func testIPBindable(ip net.IP) error {
var network, address string // "Unspecified" = let OS choose, so always bindable
if ip.To4() != nil { if ip == nil {
network, address = "udp4", "127.0.0.1:4" return nil
} else {
network, address = "udp6", "[::1]:4"
} }
dialer := net.Dialer{LocalAddr: &net.UDPAddr{IP: ip}} addr := &net.UDPAddr{IP: ip, Port: 0}
conn, err := dialer.Dial(network, address) listener, err := net.ListenUDP("udp", addr)
if err != nil { if err != nil {
return err return err
} }
conn.Close() listener.Close()
return nil return nil
} }

View File

@ -9,6 +9,7 @@ import (
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/asn1" "encoding/asn1"
"net"
"os" "os"
"testing" "testing"
@ -214,3 +215,23 @@ func getCertPoolSubjects(certPool *x509.CertPool) ([]*pkix.Name, error) {
func isUnrecoverableError(err error) bool { func isUnrecoverableError(err error) bool {
return err != nil && err.Error() != "crypto/x509: system root pool is not available on Windows" return err != nil && err.Error() != "crypto/x509: system root pool is not available on Windows"
} }
func TestTestIPBindable(t *testing.T) {
assert.Nil(t, testIPBindable(nil))
// Public services - if one of these IPs is on the machine, the test environment is too weird
assert.NotNil(t, testIPBindable(net.ParseIP("8.8.8.8")))
assert.NotNil(t, testIPBindable(net.ParseIP("1.1.1.1")))
addrs, err := net.InterfaceAddrs()
if err != nil {
t.Fatal(err)
}
for i, addr := range addrs {
if i >= 3 {
break
}
ip := addr.(*net.IPNet).IP
assert.Nil(t, testIPBindable(ip))
}
}