Skip to content
This repository has been archived by the owner on Oct 5, 2021. It is now read-only.

Commit

Permalink
Merge pull request #64 from willscott/feat/toip
Browse files Browse the repository at this point in the history
add ToIP to complement ToNetAddr
  • Loading branch information
Stebalien authored Feb 26, 2020
2 parents 07114b1 + 9a640fd commit 201fa11
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
19 changes: 19 additions & 0 deletions convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,25 @@ func FromIP(ip net.IP) (ma.Multiaddr, error) {
return FromIPAndZone(ip, "")
}

// ToIP converts a Multiaddr to a net.IP when possible
func ToIP(addr ma.Multiaddr) (net.IP, error) {
n, err := ToNetAddr(addr)
if err != nil {
return nil, err
}

switch netAddr := n.(type) {
case *net.UDPAddr:
return netAddr.IP, nil
case *net.TCPAddr:
return netAddr.IP, nil
case *net.IPAddr:
return netAddr.IP, nil
default:
return nil, fmt.Errorf("non IP Multiaddr: %T", netAddr)
}
}

// DialArgs is a convenience function that returns network and address as
// expected by net.Dial. See https://godoc.org/net#Dial for an overview of
// possible return values (we do not support the unixpacket ones yet). Unix
Expand Down
15 changes: 12 additions & 3 deletions convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,20 @@ func testToNetAddr(t *testing.T, maddr, ntwk, addr string) {
// should convert properly
switch ntwk {
case "tcp":
_ = naddr.(*net.TCPAddr)
taddr := naddr.(*net.TCPAddr)
if ip, err := ToIP(m); err != nil || !taddr.IP.Equal(ip) {
t.Fatalf("ToIP() and ToNetAddr diverged: %s != %s", taddr, ip)
}
case "udp":
_ = naddr.(*net.UDPAddr)
uaddr := naddr.(*net.UDPAddr)
if ip, err := ToIP(m); err != nil || !uaddr.IP.Equal(ip) {
t.Fatalf("ToIP() and ToNetAddr diverged: %s != %s", uaddr, ip)
}
case "ip":
_ = naddr.(*net.IPAddr)
ipaddr := naddr.(*net.IPAddr)
if ip, err := ToIP(m); err != nil || !ipaddr.IP.Equal(ip) {
t.Fatalf("ToIP() and ToNetAddr diverged: %s != %s", ipaddr, ip)
}
}
}

Expand Down

0 comments on commit 201fa11

Please sign in to comment.