Search code examples
clinuxsendto

sendto is not giving error on sending


Hi I have following code:

if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
 {
   perror("socket(UDP): ");
   return 0;
 }

 family = AF_INET;
 if((remote_server_ent = gethostbyname2(hptr, family)) == NULL )
 {
   perror("gethostbyname2");
   return 0;
 }

 if (family == AF_INET)
 {  
   sin = (struct sockaddr_in *) addr;
   sin->sin_family = AF_INET;
   sin->sin_port = htons(server_port);;
   bcopy( (char *)remote_server_ent->h_addr, (char *)&(sin->sin_addr), remote_server_ent->h_length );
   return (sizeof(struct sockaddr_in));
 }

  if (sendto(fd, msg_data_ptr, sizeof(Msg_data_hdr), 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) != sizeof(Msg_data_hdr))
  {
    fprintf(stderr, "Error in sending data to the server \n");
  }

My APP is listing on port 7000 IP 127.0.0.1. Now when i stop my application still sendto send the data, it does not give me error. I am always getting the written bytes equal the size of data which i am writting. How will i know if sending is failed or not???


Solution

  • It's UDP (SOCK_DGRAM), so you may never find out. If you need reliability guarantees, use TCP instead. If you're satisfied with a partial solution of just knowing when the receiving side is completely missing/unavailable, see here: ICMP "destination unreachable" packet on udp connected socket

    The general idea is that you can receive ICMP "destination unreachable" errors if you connect() your UDP socket and then receive data on it (you will want to use select() or epoll() for this). In some scenarios you will find out that your messages are not making it to the other side...but in other scenarios you may not, because hey, it's UDP.