Skip to content

Commit 97d8056

Browse files
authored
Merge pull request #38 from multiformats/feat/fast-loopback-check
Make the IP loopback check faster
2 parents 6040dff + ef7ebf9 commit 97d8056

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

ip.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ var (
2424
IP6Unspecified = ma.StringCast("/ip6/::")
2525
)
2626

27+
// Loopback multiaddr prefixes. Any multiaddr beginning with one of the
28+
// following byte sequences is considered a loopback multiaddr.
29+
var loopbackPrefixes = [][]byte{
30+
{ma.P_IP4, 127}, // 127.*
31+
IP6LinkLocalLoopback.Bytes(),
32+
IP6Loopback.Bytes(),
33+
}
34+
2735
// IsThinWaist returns whether a Multiaddr starts with "Thin Waist" Protocols.
2836
// This means: /{IP4, IP6}[/{TCP, UDP}]
2937
func IsThinWaist(m ma.Multiaddr) bool {
@@ -52,21 +60,14 @@ func IsThinWaist(m ma.Multiaddr) bool {
5260
}
5361

5462
// IsIPLoopback returns whether a Multiaddr is a "Loopback" IP address
55-
// This means either /ip4/127.0.0.1 or /ip6/::1
56-
// TODO: differentiate IsIPLoopback and OverIPLoopback
63+
// This means either /ip4/127.*.*.*, /ip6/::1, or /ip6/fe80::1
5764
func IsIPLoopback(m ma.Multiaddr) bool {
5865
b := m.Bytes()
59-
60-
// /ip4/127 prefix (_entire_ /8 is loopback...)
61-
if bytes.HasPrefix(b, []byte{ma.P_IP4, 127}) {
62-
return true
66+
for _, prefix := range loopbackPrefixes {
67+
if bytes.HasPrefix(b, prefix) {
68+
return true
69+
}
6370
}
64-
65-
// /ip6/::1
66-
if !m.Decapsulate(IP6Loopback).Equal(m) || !m.Decapsulate(IP6LinkLocalLoopback).Equal(m) {
67-
return true
68-
}
69-
7071
return false
7172
}
7273

net_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,18 @@ func TestIPLoopback(t *testing.T) {
314314
t.Error("IsIPLoopback failed (IP4Loopback)")
315315
}
316316

317+
if !IsIPLoopback(newMultiaddr(t, "/ip4/127.1.80.9")) {
318+
t.Error("IsIPLoopback failed (/ip4/127.1.80.9)")
319+
}
320+
321+
if IsIPLoopback(newMultiaddr(t, "/ip4/112.123.11.1")) {
322+
t.Error("IsIPLoopback false positive (/ip4/112.123.11.1)")
323+
}
324+
325+
if IsIPLoopback(newMultiaddr(t, "/ip4/192.168.0.1/ip6/::1")) {
326+
t.Error("IsIPLoopback false positive (/ip4/192.168.0.1/ip6/::1)")
327+
}
328+
317329
if !IsIPLoopback(IP6Loopback) {
318330
t.Error("IsIPLoopback failed (IP6Loopback)")
319331
}

0 commit comments

Comments
 (0)