title: Automatic port number assignment using getaddrinfo()
body: <p>*(Socket programming)*C-code for client (passing messages through UDP) is given below. We can automatically assign port number to socket by </p>
  
  <ol>
  <li>not calling bind() before sendto() <a href="https://stackoverflow.com/questions/1075399/how-to-bind-to-any-available-port">(related post)</a></li>
  <li>binding with port 0 (only provided in windows and solaris documentation for bind) that makes the kernel do automatic assignment.<a href="https://stackoverflow.com/questions/5895751/a-bind-with-a-port-of-zero-will-bind-you-to-a-free-port-is-this-portable">realted post</a></li>
  </ol>
  
  <p>However doing the same with getaddrinfo() function,passing "0"(port number) as 2nd argument assigns port 0 to socket and not any USER_RESERVED port. </p>
  
  <p>How to achieve automatic port assignment using getaddrinfo()?</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;sys/types.h&gt;
  #include&lt;sys/socket.h&gt;
  #include&lt;arpa/inet.h&gt;
  #include&lt;netdb.h&gt;
  
  int main(int argc,char *argv[])
  {
      struct addrinfo client,*cl;
      int status;
  
  
      memset(&amp;client,0,sizeof(client));//stucture should be empty
  
      client.ai_family=AF_INET;
      client.ai_socktype=SOCK_DGRAM;
      client.ai_flags=AI_PASSIVE;
  
      if(getaddrinfo(INADDR_ANY,"0",&amp;client,&amp;cl)!=0)
      {
          fprintf(stderr,"getaddrinfo: %s\n",gai_strerror(status));
          return 2;
      }
  
      int s;
      //printf("Port:: %d\n",((struct sockaddr_in*)(cl-&gt;ai_addr))-&gt;sin_port); //checking protocol number
      s=socket(cl-&gt;ai_family,cl-&gt;ai_socktype,cl-&gt;ai_protocol);
      //printf("Port:: %d\n",((struct sockaddr_in*)(cl-&gt;ai_addr))-&gt;sin_port); //checking protocol number
  
      //bind(s,cl-&gt;ai_addr,cl-&gt;ai_addrlen);
      //printf("Port:: %d\n",((struct sockaddr_in*)(cl-&gt;ai_addr))-&gt;sin_port); //checking protocol number
  
      struct sockaddr_in server;
      server.sin_family=AF_INET;
      inet_pton(AF_INET,argv[1],&amp;(server.sin_addr));
      server.sin_port=htons(4169);
      char str[100];
      for(int i=2;i&lt;argc;i++)
      {
          strncat(str,argv[i],strlen(argv[i]));
          str[strlen(str)]=' ';
      }
  
      sendto(s,str,strlen(str),0,(struct sockaddr *)&amp;server,(socklen_t)sizeof(server));
      //printf("Port:: %d\n",((struct sockaddr_in*)(cl-&gt;ai_addr))-&gt;sin_port); //checking protocol number
  
      close(s);
  }
  </code></pre>