From 245687347380d31bf4b3442e53d11e04f5d8288a Mon Sep 17 00:00:00 2001 From: Alex Vanin Date: Mon, 17 May 2021 14:59:57 +0300 Subject: [PATCH] [#522] network: Add host address stringer network.Address is a wrapper around multiaddress. Multiaddress can be resolved to ip netaddr with `IPAddrString` function: /dns4/localhost/tcp/8080 => 127.0.0.1:8080 With `HostAddrString` multi address will be transformed to host address: /dns4/localhost/tcp8080 => localhost:8080 Signed-off-by: Alex Vanin --- pkg/network/address.go | 10 ++++++++++ pkg/network/address_test.go | 39 +++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/pkg/network/address.go b/pkg/network/address.go index 3f512f333..a62f71f4b 100644 --- a/pkg/network/address.go +++ b/pkg/network/address.go @@ -46,6 +46,16 @@ func (a Address) IPAddrString() (string, error) { return ip.String(), nil } +// HostAddrString returns host address in string format. +func (a Address) HostAddrString() (string, error) { + _, host, err := manet.DialArgs(a.ma) + if err != nil { + return "", errors.Wrap(err, "could not get host addr") + } + + return host, nil +} + // AddressFromString restores address from a multiaddr string representation. func AddressFromString(s string) (*Address, error) { ma, err := multiaddr.NewMultiaddr(s) diff --git a/pkg/network/address_test.go b/pkg/network/address_test.go index 23ea712ad..a838871ee 100644 --- a/pkg/network/address_test.go +++ b/pkg/network/address_test.go @@ -28,3 +28,42 @@ func TestAddress_NetAddr(t *testing.T) { require.NoError(t, err) require.Equal(t, ip+":"+port, netAddr) } + +func TestAddress_HostAddrString(t *testing.T) { + t.Run("valid addresses", func(t *testing.T) { + testcases := []struct { + ma multiaddr.Multiaddr + exp string + }{ + {buildMultiaddr("/dns4/neofs.bigcorp.com/tcp/8080", t), "neofs.bigcorp.com:8080"}, + {buildMultiaddr("/ip4/172.16.14.1/tcp/8080", t), "172.16.14.1:8080"}, + } + + for _, testcase := range testcases { + addr := Address{testcase.ma} + + got, err := addr.HostAddrString() + require.NoError(t, err) + + require.Equal(t, testcase.exp, got) + } + }) + + t.Run("invalid addresses", func(t *testing.T) { + testcases := []multiaddr.Multiaddr{ + buildMultiaddr("/tcp/8080", t), + } + + for _, testcase := range testcases { + addr := Address{testcase} + _, err := addr.HostAddrString() + require.Error(t, err) + } + }) +} + +func buildMultiaddr(s string, t *testing.T) multiaddr.Multiaddr { + ma, err := multiaddr.NewMultiaddr(s) + require.NoError(t, err) + return ma +}