Commit bb34b84e authored by Juan Batiz-Benet's avatar Juan Batiz-Benet

Cast and Loopback

parent 5f35e6d9
...@@ -124,3 +124,21 @@ func (m *multiaddr) Split() []Multiaddr { ...@@ -124,3 +124,21 @@ func (m *multiaddr) Split() []Multiaddr {
} }
return addrs return addrs
} }
// Cast re-casts a byte slice as a multiaddr. will panic if it fails to parse.
func Cast(b []byte) Multiaddr {
_, err := bytesToString(b)
if err != nil {
panic(fmt.Errorf("multiaddr failed to parse: %s", err))
}
return &multiaddr{bytes: b}
}
// StringCast like Cast, but parses a string. Will also panic if it fails to parse.
func StringCast(s string) Multiaddr {
m, err := NewMultiaddr(s)
if err != nil {
panic(fmt.Errorf("multiaddr failed to parse: %s", err))
}
return m
}
...@@ -8,6 +8,14 @@ import ( ...@@ -8,6 +8,14 @@ import (
ma "github.com/jbenet/go-multiaddr" ma "github.com/jbenet/go-multiaddr"
) )
var (
// IP4Loopback is the ip4 loopback multiaddr
IP4Loopback = ma.StringCast("/ip4/127.0.0.1")
// IP6Loopback is the ip6 loopback multiaddr
IP6Loopback = ma.StringCast("/ip6/::1")
)
var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion") var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion")
// FromNetAddr converts a net.Addr type to a Multiaddr. // FromNetAddr converts a net.Addr type to a Multiaddr.
...@@ -150,3 +158,9 @@ func IsThinWaist(m ma.Multiaddr) bool { ...@@ -150,3 +158,9 @@ func IsThinWaist(m ma.Multiaddr) bool {
return false return false
} }
} }
// IsIPLoopback returns whether a Multiaddr is a "Loopback" IP address
// This means either /ip4/127.0.0.1 or /ip6/::1
func IsIPLoopback(m ma.Multiaddr) bool {
return m.Equal(IP4Loopback) || m.Equal(IP6Loopback)
}
...@@ -198,3 +198,21 @@ func TestListenAndDial(t *testing.T) { ...@@ -198,3 +198,21 @@ func TestListenAndDial(t *testing.T) {
cA.Close() cA.Close()
wg.Wait() wg.Wait()
} }
func TestLoopback(t *testing.T) {
if IP4Loopback.String() != "/ip4/127.0.0.1" {
t.Error("IP4Loopback incorrect:", IP4Loopback)
}
if IP6Loopback.String() != "/ip6/::1" {
t.Error("IP6Loopback incorrect:", IP6Loopback)
}
if !IsIPLoopback(IP4Loopback) {
t.Error("IsIPLoopback failed (IP4)")
}
if !IsIPLoopback(IP6Loopback) {
t.Error("IsIPLoopback failed (IP6)")
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment