title: Error receiving in UDP: Connection refused
body: <p>I am trying to send a string HI to a server over UDP in a particular port and then to receive a response. However, after I try to get the response using recvfrom() I was stuck in blocking state. I tried using connected UDP but I got:</p>
  
  <blockquote>
    <p>Error receiving in UDP: Connection refused</p>
  </blockquote>
  
  <p>What could be the reasons for this? The server is not under my control, but I do know its working fine.</p>
  
  <p>I have added the code</p>
  
  <pre><code>int sockfdudp;
  char bufudp[MAXDATASIZE], port[6];
  struct addrinfo hints, *servinfo, *p;
  struct sockaddr_storage addr;   
  int rv;
  char s[INET6_ADDRSTRLEN];
  int bytes_recv, bytes_sent;
  socklen_t len;
  
  scanf("%s",port);
  printf("UDP Port: %s \n", port);
  
  // Start connecting to datagram server  
  memset(&amp;hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_DGRAM;
  
  if ((rv = getaddrinfo(SERVER_NAME, port, &amp;hints, &amp;servinfo)) != 0) {
      fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
      return 1;
  }
  
  // loop through all the results and make a socket
  for(p = servinfo; p != NULL; p = p-&gt;ai_next) {
      if ((sockfdudp = socket(p-&gt;ai_family, p-&gt;ai_socktype,
              p-&gt;ai_protocol)) == -1) {
          perror("Creating datagram socket");
          continue;
      }
  
  if (connect(sockfdudp, p-&gt;ai_addr, p-&gt;ai_addrlen) == -1) {
          close(sockfdudp);
          perror("Connecting stream socket");
          continue;
      }
      break;
  }
  
  if (p == NULL) {
      fprintf(stderr, "ClientUDP: failed to bind socket\n");
      return 2;
  }
  
  
  freeaddrinfo(servinfo);
  
  if ((bytes_sent = sendto(sockfdudp, UDP_MSG, strlen(UDP_MSG), 0, p-&gt;ai_addr, p-&gt;ai_addrlen)) == -1) {
      perror("ClientUDP: Error sending data");
      exit(1);
  }
  printf("Data %s sent\n", UDP_MSG );     
  
  len = sizeof(struct sockaddr_storage);
  
  if ((bytes_recv = recvfrom(sockfdudp, bufudp, MAXDATASIZE-1, 0,(struct sockaddr*)&amp;addr, &amp;len)) == -1) {
      perror("Error receiving in UDP");
      exit(1);
  }
  
  printf("Bytes recv %d\n", bytes_recv);  
  
  bufudp[bytes_recv] = '\0';
  
  printf("ClientUDP: Received\n %s \n",bufudp );    
  
  close(sockfdudp);
  
  return 0;
  </code></pre>