title: TCP ports in Erlang
body: <p>I'm using Erlang to code a bittorrent client. I have been stuck for 4 days now on the same problem.</p>
  
  <p>I'm sending the handshake to all the peers with each peer having its own ip:port.</p>
  
  <p>I use gen_tcp:connect to connect. </p>
  
  <p>The problem is that I can't get their reply. I have done a lot of research and used some programs to monitor my inbound/outbound connections.</p>
  
  <p>The peers get the data and send the reply back to the port that I used to send them the handshake.</p>
  
  <p>Code wise: get_tcp:connect picks a port and uses that port to send the data to a peer. The peer replies back on that port. However, as you know in Erlang you need to use gen_tcp:listen to pick up the reply connection and you need to specify a port. In my case the port that I should be listening on is the port that gen_tcp:connect returned. </p>
  
  <p>I can get this port number using inet:port but the error is always the same: port in use. 
  I understand why I get the error, it's simply because the port I'm trying to listen on is already being used by gen_tcp:connect. I tried to close the Socket to free the port but nothing.</p>
  
  <p>So my question is: is it possible in Erlang to somehow connect to a peer and send data to it to port then listen on that same port for a reply. If not then I must somehow be able to tell the peer to send me the data back on a port I choose.</p>
  
  <p>Any ideas from all the Erlang gurus are welcome.
  Thanks,</p>
  
  <p>//Frank.</p>