Browse Source

add a function to convert a IP:port string to a WebTransport multiaddr

pull/1737/head
Marten Seemann 2 years ago
parent
commit
2110e680dd
  1. 17
      p2p/transport/webtransport/multiaddr.go
  2. 20
      p2p/transport/webtransport/multiaddr_test.go

17
p2p/transport/webtransport/multiaddr.go

@ -3,6 +3,7 @@ package libp2pwebtransport
import ( import (
"errors" "errors"
"net" "net"
"strconv"
ma "github.com/multiformats/go-multiaddr" ma "github.com/multiformats/go-multiaddr"
mafmt "github.com/multiformats/go-multiaddr-fmt" mafmt "github.com/multiformats/go-multiaddr-fmt"
@ -23,3 +24,19 @@ func toWebtransportMultiaddr(na net.Addr) (ma.Multiaddr, error) {
} }
return addr.Encapsulate(webtransportMA), nil return addr.Encapsulate(webtransportMA), nil
} }
func stringToWebtransportMultiaddr(str string) (ma.Multiaddr, error) {
host, portStr, err := net.SplitHostPort(str)
if err != nil {
return nil, err
}
port, err := strconv.ParseInt(portStr, 10, 32)
if err != nil {
return nil, err
}
ip := net.ParseIP(host)
if ip == nil {
return nil, errors.New("failed to parse IP")
}
return toWebtransportMultiaddr(&net.UDPAddr{IP: ip, Port: int(port)})
}

20
p2p/transport/webtransport/multiaddr_test.go

@ -19,3 +19,23 @@ func TestWebtransportMultiaddr(t *testing.T) {
require.EqualError(t, err, "not a UDP address") require.EqualError(t, err, "not a UDP address")
}) })
} }
func TestWebtransportMultiaddrFromString(t *testing.T) {
t.Run("valid", func(t *testing.T) {
addr, err := stringToWebtransportMultiaddr("1.2.3.4:60042")
require.NoError(t, err)
require.Equal(t, "/ip4/1.2.3.4/udp/60042/quic/webtransport", addr.String())
})
t.Run("invalid", func(t *testing.T) {
for _, addr := range [...]string{
"1.2.3.4", // missing port
"1.2.3.4:123456", // invalid port
":1234", // missing IP
"foobar",
} {
_, err := stringToWebtransportMultiaddr(addr)
require.Error(t, err)
}
})
}

Loading…
Cancel
Save