diff --git a/pkg/network/address.go b/pkg/network/address.go index 465a26aba..e581578ce 100644 --- a/pkg/network/address.go +++ b/pkg/network/address.go @@ -2,6 +2,8 @@ package network import ( "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr-net" + "github.com/pkg/errors" ) // Address represents the NeoFS node @@ -14,6 +16,16 @@ func (a Address) String() string { return a.ma.String() } +// NetAddr returns network endpoint address in string format. +func (a Address) NetAddr() string { + ip, err := manet.ToNetAddr(a.ma) + if err != nil { + panic(errors.Wrap(err, "could not get net addr")) + } + + return ip.String() +} + // AddressFromString restores address from a 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 new file mode 100644 index 000000000..e53b7bfb5 --- /dev/null +++ b/pkg/network/address_test.go @@ -0,0 +1,28 @@ +package network + +import ( + "strings" + "testing" + + "github.com/multiformats/go-multiaddr" + "github.com/stretchr/testify/require" +) + +func TestAddress_NetAddr(t *testing.T) { + ip := "127.0.0.1" + port := "8080" + + ma, err := multiaddr.NewMultiaddr(strings.Join([]string{ + "/ip4", + ip, + "tcp", + port, + }, "/")) + + require.NoError(t, err) + + addr, err := AddressFromString(ma.String()) + require.NoError(t, err) + + require.Equal(t, ip+":"+port, addr.NetAddr()) +}