title: How does the socket API accept() function work?
body: <p>The socket API is the de-facto standard for TCP/IP and UDP/IP communications (that is, networking code as we know it). However, one of its core functions, <code>accept()</code> is a bit magical.</p>
  
  <p>To borrow a semi-formal definition:</p>
  
  <blockquote>
    <p>accept() is used on the server side.
    It accepts a received incoming attempt
    to create a new TCP connection from
    the remote client, and creates a new
    socket associated with the socket
    address pair of this connection.</p>
  </blockquote>
  
  <p>In other words, <code>accept</code> returns a new socket through which the server can communicate with the newly connected client. The old socket (on which <code>accept</code> was called) stays open, on the same port, listening for new connections.</p>
  
  <p>How does <code>accept</code> work? How is it implemented? There's a lot of confusion on this topic. Many people claim accept opens a new port and you communicate with the client through it. But this obviously isn't true, as no new port is opened. You actually can communicate through the same port with different clients, but how? When several threads call <code>recv</code> on the same port, how does the data know where to go?</p>
  
  <p>I guess it's something along the lines of the client's address being associated with a socket descriptor, and whenever data comes through <code>recv</code> it's routed to the correct socket, but I'm not sure.</p>
  
  <p>It'd be great to get a thorough explanation of the inner-workings of this mechanism.</p>