net.Addr -> Multiaddr

This commit is contained in:
Juan Batiz-Benet 2014-09-13 04:48:56 -07:00
parent a4b7753f74
commit 0624ab3bf7
2 changed files with 126 additions and 0 deletions

77
net.go Normal file
View File

@ -0,0 +1,77 @@
package multiaddr
import (
"fmt"
"net"
)
var errIncorrectNetAddr = fmt.Errorf("incorrect network addr conversion")
// FromNetAddr converts a net.Addr type to a Multiaddr.
func FromNetAddr(a net.Addr) (*Multiaddr, error) {
switch a.Network() {
case "tcp", "tcp4", "tcp6":
ac, ok := a.(*net.TCPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
// Get IP Addr
ipm, err := FromIP(ac.IP)
if err != nil {
return nil, errIncorrectNetAddr
}
// Get TCP Addr
tcpm, err := NewMultiaddr(fmt.Sprintf("/tcp/%d", ac.Port))
if err != nil {
return nil, errIncorrectNetAddr
}
// Encapsulate
return ipm.Encapsulate(tcpm), nil
case "udp", "upd4", "udp6":
ac, ok := a.(*net.UDPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
// Get IP Addr
ipm, err := FromIP(ac.IP)
if err != nil {
return nil, errIncorrectNetAddr
}
// Get UDP Addr
udpm, err := NewMultiaddr(fmt.Sprintf("/udp/%d", ac.Port))
if err != nil {
return nil, errIncorrectNetAddr
}
// Encapsulate
return ipm.Encapsulate(udpm), nil
case "ip", "ip4", "ip6":
ac, ok := a.(*net.IPAddr)
if !ok {
return nil, errIncorrectNetAddr
}
return FromIP(ac.IP)
default:
return nil, fmt.Errorf("unknown network %v", a.Network())
}
}
// FromIP converts a net.IP type to a Multiaddr.
func FromIP(ip net.IP) (*Multiaddr, error) {
switch {
case ip.To4() != nil:
return NewMultiaddr("/ip4/" + ip.String())
case ip.To16() != nil:
return NewMultiaddr("/ip6/" + ip.String())
default:
return nil, errIncorrectNetAddr
}
}

49
net_test.go Normal file
View File

@ -0,0 +1,49 @@
package multiaddr
import (
"net"
"testing"
)
type GenFunc func() (*Multiaddr, error)
func testConvert(t *testing.T, s string, gen GenFunc) {
m, err := gen()
if err != nil {
t.Fatal("failed to generate.")
}
if s2, _ := m.String(); err != nil || s2 != s {
t.Fatal("failed to convert: " + s + " != " + s2)
}
}
func TestFromIP4(t *testing.T) {
testConvert(t, "/ip4/10.20.30.40", func() (*Multiaddr, error) {
return FromIP(net.ParseIP("10.20.30.40"))
})
}
func TestFromIP6(t *testing.T) {
testConvert(t, "/ip6/2001:4860:0:2001::68", func() (*Multiaddr, error) {
return FromIP(net.ParseIP("2001:4860:0:2001::68"))
})
}
func TestFromTCP(t *testing.T) {
testConvert(t, "/ip4/10.20.30.40/tcp/1234", func() (*Multiaddr, error) {
return FromNetAddr(&net.TCPAddr{
IP: net.ParseIP("10.20.30.40"),
Port: 1234,
})
})
}
func TestFromUDP(t *testing.T) {
testConvert(t, "/ip4/10.20.30.40/udp/1234", func() (*Multiaddr, error) {
return FromNetAddr(&net.UDPAddr{
IP: net.ParseIP("10.20.30.40"),
Port: 1234,
})
})
}