diff --git a/pkg/portutil/portutil.go b/pkg/portutil/portutil.go index f0ffe9b96de..ad2848c4e47 100644 --- a/pkg/portutil/portutil.go +++ b/pkg/portutil/portutil.go @@ -31,20 +31,19 @@ import ( // return respectively ip, hostPort, containerPort func splitParts(rawport string) (string, string, string) { - parts := strings.Split(rawport, ":") - n := len(parts) - containerport := parts[n-1] + lastIndex := strings.LastIndex(rawport, ":") + containerPort := rawport[lastIndex+1:] + if lastIndex == -1 { + return "", "", containerPort + } - switch n { - case 1: - return "", "", containerport - case 2: - return "", parts[0], containerport - case 3: - return parts[0], parts[1], containerport - default: - return strings.Join(parts[:n-2], ":"), parts[n-2], containerport + hostAddrPort := rawport[:lastIndex] + addr, port, err := net.SplitHostPort(hostAddrPort) + if err != nil { + return "", hostAddrPort, containerPort } + + return addr, port, containerPort } // ParseFlagP parse port mapping pair, like "127.0.0.1:3000:8080/tcp", diff --git a/pkg/portutil/portutil_test.go b/pkg/portutil/portutil_test.go index 87f0f5dc892..e3ec270c2b5 100644 --- a/pkg/portutil/portutil_test.go +++ b/pkg/portutil/portutil_test.go @@ -357,6 +357,21 @@ func TestParseFlagP(t *testing.T) { }, wantErr: false, }, + { + name: "with ipv6 host ip", + args: args{ + s: "[::0]:8080:80/tcp", + }, + want: []gocni.PortMapping{ + { + HostPort: 8080, + ContainerPort: 80, + Protocol: "tcp", + HostIP: "::0", + }, + }, + wantErr: false, + }, { name: "with invalid protocol", args: args{