Trevor
Trevor

Reputation: 6689

Prevent UDP data from being sent when network connection is unavailable

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);

Upvotes: 0

Views: 212

Answers (2)

Chris Cleeland
Chris Cleeland

Reputation: 4900

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.

Upvotes: 2

C&#233;dric Julien
C&#233;dric Julien

Reputation: 80821

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.

Upvotes: 0

Related Questions