0

I have a C application that sends data to a UDP server every few seconds. If the client loses it's network connection for a few minutes and then gets it's connection back, it will send all of the accumulated data to the server which may result in a hundred or more requests coming into the server at the same time from that client.

Is there any way to prevent these messages from being sent from the client if an error occurs during transmission using UDP? Would a connect call from the UDP client help to determine if the client can connect to the server? Or would this only be possible using TCP?

int socketDescriptor; 
struct sockaddr_in serverAddress;

if ((socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
    printf("Could not create socket. \n");
    return;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(server_ip);
serverAddress.sin_port = htons(server_port);

if (sendto(socketDescriptor, data, strlen(data), 0, 
                  (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
{  
   printf("Could not send data to the server. \n");
   return;
}

close(socketDescriptor);
Trevor
  • 6,659
  • 5
  • 35
  • 68
  • When you say "the client loses it's[sic] network connection" do you mean that somebody pulled the plug or something similar? AFAIK connect() won't help you; it's simply a convenience so that you don't have to specify the destination address in every send() call. With UDP, connect() doesn't trigger any network activity because UDP is not connected and no segments must be exchanged. – Chris Cleeland May 13 '11 at 13:05

2 Answers2

2

It sounds like the behavior you're getting is from datagrams being buffered in socket sndbuf, and you would prefer that those datagrams be dropped if they can't immediately be sent?

If that's the case, you might have luck setting the size of the sndbuf to zero.

Word of warning--this area of behavior sounds like it treads very close to "implementation specific" territory.

Chris Cleeland
  • 4,760
  • 3
  • 26
  • 28
0

As explained here, to retrieve errors on UDP send you should use a connect before, then the send method, yet on Linux it seems to have the same behaviour with or without connect.

Community
  • 1
  • 1
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132