Libp2p ListenAddrs failed to connect to remote server

m1, _ := multiaddr.NewMultiaddr("/ip4/121.42.145.216/tcp/4001")
m2, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/4001")
srvHost := newHost(t, m1)
clientHost := newHost(t, m2)
func newHost(t *testing.T, listen multiaddr.Multiaddr) host.Host {
h, err := libp2p.New(
context.Background(),
libp2p.ListenAddrs(listen),
)
if err != nil {
t.Fatal(err)
}
return h
}

Connect to “/ip4/127.0.0.1/tcp/4001” succeed.
Connect to “/ip4/121.42.145.216/tcp/4001/” or “/ip4/121.42.145.216/tcp/4001/ipfs/QmWKJoZuWMQEJpfsGNBsDqcnMRcPYbZjKCH76d7cwGMdCo” failed, with the error: failed to listen on any address:[listen tcp4 121.42.145.216:4001:bind:can’t assign requested address]
The public ip 121.42.145.216 is my remote cloud server in Aliyun.
I have already added the nodes for my labtap and the cloud server by “ipfs swarm connect” successfully.

How to use libp2p.ListenAddrs to connect to remote server?

ListenAddrs specifies the address you’re node is listening on. That second command is failing because you’re trying to listen on an IP address that hasn’t been assigned to your machine.

If you want to connect to a remote host, use h.Connect(...) (or just use h.NewStream(remotePeer, someProtocolName) to open a new stream).

Thanks for pointing this. @stebalien

I am trying to use gostream.Listen() method in the demo.

// Listen provides a standard net.Listener ready to accept “connections”.
// Under the hood, these connections are libp2p streams tagged with the
// given protocol.ID.
func Listen(h host.Host, tag protocol.ID) (net.Listener, error) {
ctx, cancel := context.WithCancel(context.Background())

l := &listener{
	host:     h,
	ctx:      ctx,
	cancel:   cancel,
	tag:      tag,
	streamCh: make(chan pnet.Stream),
}
h.SetStreamHandler(tag, func(s pnet.Stream) {
	select {
	case l.streamCh <- s:
	case <-ctx.Done():
		s.Reset()
	}
})
return l, nil

}

Is there any way to get a HOST using libp2p.New for a remote node?

Is there any way to get a HOST using libp2p.New for a remote node?

No. A Host is a local node. That example is listening for all connections to the passed host that uses the specified protocol name.