Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net: fix addr2Host for backwards compatibility with isLocalhost() #906

Merged
merged 1 commit into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion net_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package forwarder

import (
"net"
"slices"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
Expand Down Expand Up @@ -63,7 +64,17 @@ func addr2Host(addr string) string {
return "unknown"
}

if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
commonLocalhostNames := []string{
"localhost",
"127.0.0.1",
"::1",
"::",
}
if slices.Contains(commonLocalhostNames, host) {
return "localhost"
}

if ip := net.ParseIP(host); ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) {
return "localhost"
}

Expand Down
26 changes: 26 additions & 0 deletions net_metrics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright 2022-2024 Sauce Labs Inc., all rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

package forwarder

import (
"testing"
)

func TestAddr2HostLocalhost(t *testing.T) {
addrs := []string{
"localhost:80",
"127.0.0.100:80",
"[::1]:80",
"[::]:52367",
}

for _, addr := range addrs {
if host := addr2Host(addr); host != "localhost" {
t.Fatalf("addr2Host(%q): got %q, want localhost", addr, host)
}
}
}