Search code examples
tcpbittorrent

Avoiding double inbound/outbound connection between bittorrent peers


I am implementing a bittorrent client in Elixir as a learning exercise.

Reading multiple docs, it appears that a proper client should not only be able to create outbound socket connections but also listen on a port and accept inbound connections.

But I cannot find docs about Alice and Bob trying to connect to each other simultaneously.

That would end up with two connections with the same peer (for the same info hash / torrent). Now if I want to track my connections the reasonable thing seems to associate them with the torrent id + peer id, which means boths connections would have the same identifier.

Is there something I missed that prevents that case? Or do clients generally just close one of the two connections randomly? Or maybe the IP (and even port) can be part of the ID so keep both connections is actually OK (though useless I guess).

What would be the proper solution?

Thank you.


Solution

  • Or do clients generally just close one of the two connections randomly?

    More or less that, although with some biases such as preferring the longer-lived connection to stay alive or with some randomized delay to prevent simultaneous close attempts.

    The situation that two clients initiate a connection to each other at the same time is not that common anyway, most of the time things will be different enough between peers that one will be clearly arrive first and then the other side will know about it and avoid the reverse attempt.

    Sidenote: One shouldn't trust the peer ID too much. It's useful, but an adversarial client could intentionally pick the ID of another one or randomize it on every connection.