I'm trying to write a udp client program that will detect if the server went down. This program is for a linux or BSD system. Here's a short test program:
Code:
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h> /*sleep()*/
int main(int argc, char**argv)
{
int srcsock;
struct sockaddr_in server_addr;
char sendst[1000];
int PORTNUM = 4000;
int numrec, res, junk;
srcsock=socket(AF_INET,SOCK_DGRAM,0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr=inet_addr(argv[1]);
server_addr.sin_port=htons(PORTNUM);
connect(srcsock, (struct sockaddr *)&server_addr, sizeof(server_addr));
sleep(1);
strcpy(sendst,"This is just junk1");
numrec = write(srcsock,sendst,strlen(sendst));
printf("%d\n", numrec);
sleep(1);
strcpy(sendst,"This is just junk2");
numrec = write(srcsock,sendst,strlen(sendst));
printf("%d\n", numrec);
sleep(1);
strcpy(sendst,"This is just junk3");
numrec = write(srcsock,sendst,strlen(sendst));
printf("%d\n", numrec);
sleep(1);
strcpy(sendst,"This is just junk4");
numrec = write(srcsock,sendst,strlen(sendst));
printf("%d\n", numrec);
sleep(1);
strcpy(sendst,"This is just junk5");
numrec = write(srcsock,sendst,strlen(sendst));
printf("%d\n", numrec);
close(srcsock);
}
The return from this is the correct string length for each string if the server is up, but when the server is down when I run the program, it returns:
19
-1
19
-1
19
Is there a reliable way to detect if the remote server died either during the message, or if the message could not be sent? I know it's UDP, but other programs seem to have this ability.