How to connect to nodes only knowing their ip and port?

I want to do a simulation with several nodes on different machines. I know IP addresses of all these machines and also ports they are listening to. How can I use host.Connect to connect to those nodes? I have tried to create a multiaddr from the ip address and port but there was an error stating that the address is not a valid p2p address.

Interesting question… I think this is not possible to host.Connectwithout knowing the peer ID.

Assuming you know the machines and ports, you could also pregenerate the peer keys/IDs ?

Also, libp2p peer use mDNS for autodiscovery, which essentially is broadcasting their full addresses and peer IDs to the local network. If you are in a local network, you could try letting all peers discover each others automatically (https://github.com/libp2p/go-libp2p/blob/master/p2p/discovery/mdns.go).

Bringing this 2019 thread to life…

This is the approach we have taken to connect to nodes knowing their IP and Port and not knowing their peerId.

This works on go-libp2p:

  1. Construct a multiaddr with the IP, Port and a random fake PeerId
  2. Try to connect and get an ErrPeerIDMismatch error, the error includes the actual PeerId of the peer.
  3. Replace the fake peerId with the actual peerId from the ErrPeerIDMismatch error
  4. Try to connect a second time, now using the actual peerId

Maybe this can be supported directly by the library in the future for cases where peerId is not provided by the library user (instead of the behavior of reporting it to have a non a valid p2p address).

Alternatively, a feature can be added to query a peer for its peerId based on its IP and Port (or a multiaddress of any multiaddress type without the peerId) - such feature can rely internally on the ErrPeerIDMismatch error.

1 Like