title: How to send UDP message to loopback address and then read from it?
body: <p>I have a c program. it first tries to send UDP message to the loopback address, then read from the the loopback. 
  But first the sendto() function fails with the message "<strong>sendto fails: Invalid argument</strong>".
  The code looks like:</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;stdio.h&gt;
  
  int main(void)
  {
      struct sockaddr_in servaddr;
      int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  
      bzero(&amp;servaddr, sizeof(servaddr));
  
      struct in_addr addr;
      char dottedaddr[20];
      inet_aton("127.0.0.1", &amp;addr);
  
          servaddr.sin_family      = AF_INET;
          servaddr.sin_addr.s_addr = addr.s_addr;
          servaddr.sin_port        = htons(0);
  
      struct sockaddr_in cliaddr;
  
          inet_aton("192.168.2.12", &amp;addr);
  
          cliaddr.sin_family      = AF_INET;
          cliaddr.sin_addr.s_addr = addr.s_addr;
          cliaddr.sin_port        = htons(5000);
  
  
      if(bind(sockfd, (const struct sockaddr *)&amp;cliaddr, sizeof(cliaddr)) == -1)
      {
          perror("bind failed");
          exit(1);
      }
  
      char buf[] = {'h', 'i', ' ', 'i', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u', 0};
  
  
      if( sendto(sockfd, buf, sizeof(buf), 0, (const struct sockaddr *)&amp;servaddr, sizeof(servaddr)) == -1)
      {
          perror("sendto fails");
          exit(2);
      }
  
      fd_set readFd;
      FD_ZERO(&amp;readFd);
      FD_SET(sockfd, &amp;readFd);
      struct timeval timeout;
      timeout.tv_sec = 5;
      timeout.tv_usec = 0;
  
      int ret = select(sockfd + 1, &amp;readFd, NULL, NULL, &amp;timeout);
      if(ret &gt; 0)
      {
          if(FD_ISSET(sockfd, &amp;readFd))
          {
              char buf2[21];
              struct sockaddr_in from;
              int len = sizeof(from);
              if(recvfrom(sockfd, buf2, sizeof(buf2), 0, (struct sockaddr *)&amp;from, &amp;len) == -1)
              {
                  perror("recvfrom fails");
              }
          }
      }
      else if (ret == 0)
      {
          printf("select time out \n");
      }
      else
      {
          printf("select fails");
      }
  
  }
  </code></pre>
  
  <p>if i change the server port from 0 to 5000, then sendto() can succeed. What is the reason ?</p>
  
  <p>The second question is, after the server port is changed to 5000, the select() cannot detect the socket is readable or not. It simply timeout. I think sockfd should be readable since i just send a message to the loopback address. Is there anything wrong with the code?
  thank you!</p>