title: Get Local Port used by Socket
body: <p>I need to get the local port used by a (client) socket.</p>
  
  <p>It was my understanding that <code>Windows Sockets performs an implicit bind function call</code>, therefore <code>getsockname()</code> after <code>sendto()</code> should provide the assigned port. However, it always sets 0 as the port number. Am I missing something?</p>
  
  <p>ex:  </p>
  
  <pre><code>if (sendto(sockfd, ...) != SOCKET_ERROR)
      printf("Sent\n");
  
  if (getsockname(sockfd, (struct sockaddr*)&amp;sin, &amp;sinlen) != SOCKET_ERROR)
      printf("port = %u\n", ntohs(sin.sin_port);
  else
      printf("Error");
  
  //result: Sent, port = 0
  </code></pre>