Connecting two instances on the same local machine

Hi! My previous message on Monday was filtered by your spam filter, hopefully this one will get through. I’m trying to connect two nodes using libp2p in Go. The first instance starts fine and connects to bootstrap nodes. The second one gives errors like the following:

 discovered new local peer 12D3KooWKDh34VB9v5FrJSKozxCLxPGRjTEauxBbuxBjS84vg
Q5S error connecting to local peer 12D3KooWKDh34VB9v5FrJSKozxCLxPGRjTEauxBbuxBjS84vg
 Q5S: failed to dial 12D3KooWKDh34VB9v5FrJSKozxCLxPGRjTEauxBbuxBjS84vgQ5S: no good addresses

The two instances use two different private keys. What am I doing wrong? I’d appreciate any help!

Here is how I set up the connection in Go:

    // create the host
	n.host, err = libp2p.New(n.ctx,
		libp2p.ListenAddrStrings(
			"/ip4/0.0.0.0/tcp/4001",      // regular tcp connections over IPv4
			"/ip4/0.0.0.0/udp/4001/quic", // a UDP endpoint for the QUIC transport
			"/ip6/::/tcp/4001",           // tcp over IPv6
			"/ip4/127.0.0.1/tcp/0",       // same machine loopback interface
		),
		libp2p.Identity(privkey),
		libp2p.NATPortMap(),
		// support TLS connections
		libp2p.Security(libp2ptls.ID, libp2ptls.New),
		// support secio connections
		libp2p.Security(secio.ID, secio.New),
		// support QUIC
		libp2p.Transport(libp2pquic.NewTransport),
		libp2p.DefaultTransports,
		libp2p.ConnectionManager(connmgr.NewConnManager(
			100,         // Lowwater
			400,         // HighWater,
			time.Minute, // GracePeriod
		)),
		// routing DHT
		libp2p.Routing(func(h host.Host) (routing.PeerRouting, error) {
			n.dht, err = dht.New(n.ctx, h)
			return n.dht, err
		}),
		libp2p.EnableAutoRelay())

Nevermind, I found the problem. The error is caused because both instances are trying to listen on local port 4001, so the second one refuses to dial to this port. If I replace the 4001 with 0 in the above code, they connect and can exchange messages!