Skip to content

Commit 50cc0e4

Browse files
committed
robust DialArgs
1 parent 5bd241d commit 50cc0e4

File tree

1 file changed

+60
-24
lines changed

1 file changed

+60
-24
lines changed

convert.go

Lines changed: 60 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package manet
33
import (
44
"fmt"
55
"net"
6-
"strings"
76

87
ma "github.com/multiformats/go-multiaddr"
98
)
@@ -82,31 +81,68 @@ func FromIP(ip net.IP) (ma.Multiaddr, error) {
8281

8382
// DialArgs is a convenience function returning arguments for use in net.Dial
8483
func DialArgs(m ma.Multiaddr) (string, string, error) {
85-
// TODO: find a 'good' way to eliminate the function.
86-
// My preference is with a multiaddr.Format(...) function
87-
if !IsThinWaist(m) {
88-
return "", "", fmt.Errorf("%s is not a 'thin waist' address", m)
89-
}
90-
91-
str := m.String()
92-
parts := strings.Split(str, "/")[1:]
93-
94-
if len(parts) == 2 { // only IP
95-
return parts[0], parts[1], nil
96-
}
97-
98-
network := parts[2]
99-
100-
var host string
101-
switch parts[0] {
102-
case "ip4":
103-
network = network + "4"
104-
host = strings.Join([]string{parts[1], parts[3]}, ":")
84+
var (
85+
zone, network, ip, port string
86+
)
87+
88+
ma.ForEach(m, func(c ma.Component) bool {
89+
switch network {
90+
case "":
91+
switch c.Protocol().Code {
92+
case ma.P_IP6ZONE:
93+
zone = c.Value()
94+
return true
95+
case ma.P_IP6:
96+
network = "ip6"
97+
ip = c.Value()
98+
return true
99+
case ma.P_IP4:
100+
network = "ip4"
101+
ip = c.Value()
102+
return true
103+
}
104+
case "ip4":
105+
switch c.Protocol().Code {
106+
case ma.P_UDP:
107+
network = "udp4"
108+
case ma.P_TCP:
109+
network = "tcp4"
110+
default:
111+
return false
112+
}
113+
port = c.Value()
114+
case "ip6":
115+
switch c.Protocol().Code {
116+
case ma.P_UDP:
117+
network = "udp6"
118+
case ma.P_TCP:
119+
network = "tcp6"
120+
default:
121+
return false
122+
}
123+
port = c.Value()
124+
}
125+
// Done.
126+
return false
127+
})
128+
switch network {
105129
case "ip6":
106-
network = network + "6"
107-
host = fmt.Sprintf("[%s]:%s", parts[1], parts[3])
130+
if zone != "" {
131+
ip += "%" + zone
132+
}
133+
fallthrough
134+
case "ip4":
135+
return network, ip, nil
136+
case "tcp4", "udp4":
137+
return network, ip + ":" + port, nil
138+
case "tcp6", "udp6":
139+
if zone != "" {
140+
ip += "%" + zone
141+
}
142+
return network, "[" + ip + "]" + ":" + port, nil
143+
default:
144+
return "", "", fmt.Errorf("%s is not a 'thin waist' address", m)
108145
}
109-
return network, host, nil
110146
}
111147

112148
func parseTCPNetAddr(a net.Addr) (ma.Multiaddr, error) {

0 commit comments

Comments
 (0)