title: bind() server socket to any port always gives port no. 0
body: <p>I need to bind my server to a dynamic port (use an ephermal port) but call to bind() when port is specified to be 0 (which means any random port) is always binding the server to port 0. </p>
  
  <p>//Sample code snippet</p>
  
  <pre><code>int sockfd;
  struct sockaddr_in serv_addr;
  
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd &lt; 0)
     error("ERROR opening socket");
  bzero((char *) &amp;serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(INADDR_ANY);  //randomly selected port
  if (bind(sockfd, (struct sockaddr *) &amp;serv_addr, sizeof(serv_addr)) &lt; 0)
    error("ERROR on binding");
  
  listen(sockfd,5);
  
  printf("Port no. is %d",ntohs (serv_addr.sin_port));
  close(sockfd);
  </code></pre>