net: added InterfaceMultiaddrs

This commit is contained in:
Juan Batiz-Benet 2014-11-05 00:38:21 -08:00
parent bb34b84e84
commit 4489dfa8c5
6 changed files with 50 additions and 16 deletions

View File

@ -7,17 +7,15 @@ import (
"os"
ma "github.com/jbenet/go-multiaddr"
manet "github.com/jbenet/go-multiaddr/net"
)
var usage = `multiaddr conversion
usage: multiaddr [fmt] <>`
var formats = []string{"string", "bytes", "hex", "raw"}
var formats = []string{"string", "bytes", "hex", "slice"}
var format string
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s <multiaddr>\n\nFlags:\n", os.Args[0])
fmt.Fprintf(os.Stderr, "usage: %s [<multiaddr>]\n\nFlags:\n", os.Args[0])
flag.PrintDefaults()
}
@ -29,8 +27,14 @@ func init() {
func main() {
flag.Parse()
args := flag.Args()
if len(args) != 1 {
die("error: can only take one argument")
if len(args) == 0 {
maddrs, err := manet.InterfaceMultiaddrs()
if err != nil {
die(err)
}
output(maddrs...)
return
}
m, err := ma.NewMultiaddr(args[0])
@ -38,16 +42,22 @@ func main() {
die(err)
}
fmt.Println(outfmt(m))
output(m)
}
func output(ms ...ma.Multiaddr) {
for _, m := range ms {
fmt.Println(outfmt(m))
}
}
func outfmt(m ma.Multiaddr) string {
switch format {
case "string":
return m.String()
case "bytes":
case "slice":
return fmt.Sprintf("%v", m.Bytes())
case "raw":
case "bytes":
return string(m.Bytes())
case "hex":
return "0x" + hex.EncodeToString(m.Bytes())

View File

@ -1,4 +1,4 @@
package net
package manet
import (
"fmt"
@ -70,6 +70,13 @@ func FromNetAddr(a net.Addr) (ma.Multiaddr, error) {
}
return FromIP(ac.IP)
case "ip+net":
ac, ok := a.(*net.IPNet)
if !ok {
return nil, errIncorrectNetAddr
}
return FromIP(ac.IP)
default:
return nil, fmt.Errorf("unknown network %v", a.Network())
}

View File

@ -1,4 +1,4 @@
package net
package manet
import (
"net"

View File

@ -1,5 +1,5 @@
// Package net provides Multiaddr specific versions of common
// Package manet provides Multiaddr specific versions of common
// functions in stdlib's net package. This means wrappers of
// standard net symbols like net.Dial and net.Listen, as well
// as conversion to/from net.Addr.
package net
package manet

View File

@ -1,4 +1,4 @@
package net
package manet
import (
"fmt"
@ -216,3 +216,20 @@ func Listen(laddr ma.Multiaddr) (Listener, error) {
laddr: laddr,
}, nil
}
// InterfaceMultiaddrs will return the addresses matching net.InterfaceAddrs
func InterfaceMultiaddrs() ([]ma.Multiaddr, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
maddrs := make([]ma.Multiaddr, len(addrs))
for i, a := range addrs {
maddrs[i], err = FromNetAddr(a)
if err != nil {
return nil, err
}
}
return maddrs, nil
}

View File

@ -1,4 +1,4 @@
package net
package manet
import (
"bytes"