diff --git a/server/listener_unix.go b/server/listener_unix.go index 51a9e80..2c3efd0 100644 --- a/server/listener_unix.go +++ b/server/listener_unix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package server @@ -15,10 +16,10 @@ func init() { func reuseportMakeListener(s *Server, address string) (ln net.Listener, err error) { var network string - if validIP4(address) { - network = "tcp4" - } else { + if validIP6(address) { network = "tcp6" + } else { + network = "tcp4" } return reuseport.NewReusablePortListener(network, address) diff --git a/server/server.go b/server/server.go index d2525ed..2b91700 100644 --- a/server/server.go +++ b/server/server.go @@ -1008,3 +1008,17 @@ func validIP4(ipAddress string) bool { return ip4Reg.MatchString(ipAddress) } + +func validIP6(ipAddress string) bool { + ipAddress = strings.Trim(ipAddress, " ") + i := strings.LastIndex(ipAddress, ":") + ipAddress = ipAddress[:i] // remove port + ipAddress = strings.TrimPrefix(ipAddress, "[") + ipAddress = strings.TrimSuffix(ipAddress, "]") + ip := net.ParseIP(ipAddress) + if ip != nil && ip.To4() == nil { + return true + } else { + return false + } +} diff --git a/server/server_test.go b/server/server_test.go index c8b40b4..3e36328 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -178,3 +178,26 @@ func TestHandler(t *testing.T) { assert.Equal(t, "{\"C\":200}", string(resp.Payload)) } + +func Test_validIP6(t *testing.T) { + type args struct { + ipAddress string + } + tests := []struct { + name string + args args + want bool + }{ + {"1", args{ipAddress: "[CDCD:910A:2222:5498:8475:1111:3900:2020]:8080"}, true}, + {"2", args{ipAddress: "[1030::C9B4:FF12:48AA:1A2B]:8080"}, true}, + {"3", args{ipAddress: "[2000:0:0:0:0:0:0:1]:8080"}, true}, + {"4", args{ipAddress: "127.0.0.1:8080"}, false}, + {"5", args{ipAddress: "localhost:8080"}, false}, + {"6", args{ipAddress: "127.1:8080"}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equalf(t, tt.want, validIP6(tt.args.ipAddress), "validIP6(%v)", tt.args.ipAddress) + }) + } +}