/* cludp.c Client code, UDP, from Padovano, "Networking Applications on Unix System V Release 4", Prentice-Hall, page 518.. (slightly modified to receive server port from command line) This is a way to call this program cludp fowler joda.cis.temple.edu 3221 Assuming that there is an svudp program running on joda with port 3221, cludp will report if fowler is or not logged on joda. */ #include #include #include #include #include #include /*#define SERV_PORT 2345*/ #define MAXNAME 1024 #define NUM_TRIES 20 int timed_out; main(argc, argv) int argc; char **argv; { int fd; /* fd into transport provider */ char buf[MAXNAME]; /* holds message from server */ int tries = NUM_TRIES; /* number of tries to send */ int got_it = 0; /* determine datagram receipt */ struct hostent *hp; /* holds address of server */ struct sockaddr_in myaddr; /* holds the local address */ struct sockaddr_in servaddr; /* holds the server address */ int length; /* length of user name */ int size; /* size of sockaddr structure */ void handler(); /* handles time out signals */ /* Check for proper usage */ if (argc != 4) { fprintf(stderr, "Usage: %s user server port\n", argv[0]); exit(2); } /* Open the socket into UDP/IP */ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket failed"); exit(1); } /* Bind to an arbitrary return address */ bzero((char *)&myaddr, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(0); if (bind(fd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); exit(1); } /* Fill in the server's UDP/IP address. */ bzero((char *)&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[3])); /*htons(SERV_PORT);*/ hp = gethostbyname(argv[2]); if (hp == 0) { fprintf(stderr, "could not obtain address of %s\n", argv[2]); return (-1); } bcopy(hp->h_addr_list[0], (caddr_t)&servaddr.sin_addr, hp->h_length); length = strlen(argv[1]) + 1; size = sizeof(servaddr); /* Loop up to the specified number of tries. */ while (tries --) { if(sendto(fd, argv[1], length, 0, (struct sockaddr *)&servaddr, size) != length) { perror("sendto failed!\n"); exit(1); } /* Allow 15 seconds for response to arrive */ timed_out = 0; signal(SIGALRM, handler); if (recvfrom(fd, buf, MAXNAME, 0, (struct sockaddr *)0, (int *)0) >= 0) { alarm(0); got_it = 1; break; } if (timed_out) { continue; } fprintf(stderr, "recvfrom failed!\n"); exit(1); } if (!got_it) { printf("failed %d times, exiting\n", NUM_TRIES); exit(1); } if (buf[0] == 'y') { printf("%s is logged on server\n", argv[1]); } else { printf("%s is not logged on server\n", argv[1]); } exit(0); } void handler() { timed_out = 1; }