/* cludp1.c - Client using datagram service on sockets It has two command line parameters: a host name, and a port number. It sends the current time to the server, waits for and prints the reply, and repeats after waiting for 30 seconds. */ #include #include #include #include #include #include #include #include #include #define MAXBUF 2 * 1024 int main(int argc, char *argv[]) { int sock; /* file descriptor for socket */ long tm; /* time */ struct sockaddr_in name; /* Address of the server */ struct hostent *hp; char data[MAXBUF]; if (argc != 3){ printf("Usage %s servername portnumber\n", argv[0]); exit(0); } /* create a socket */ sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock < 0) { perror("Opening datagram socket"); exit(1); } /* Host and port come from input arguments */ /* Fill in the server's UDP address */ hp = gethostbyname(argv[1]); if(hp == 0) { fprintf(stderr, " %s: unknown host",argv[1]); printf("Error h_errno %d\n", h_errno); exit(2); } bcopy((char *)hp->h_addr, (char *)&name.sin_addr, hp->h_length); name.sin_family = AF_INET; name.sin_port = htons(atoi(argv[2])); while (1) { /* send the message */ time((time_t *)&tm); printf("At Client: Current time is %s\n", ctime((time_t *)&tm)); strcpy(data, ctime((time_t *)&tm)); if(sendto(sock, data, strlen(data) * sizeof(char), 0, (struct sockaddr *)&name, sizeof(name)) < 0) perror("Sending datagram message"); /* Wait for the reply */ if(read(sock, data,(1024 * 2)) < 0) { perror("Error receving data from server"); exit(1); } printf("Data from server %s\n", data); sleep(30); } close(sock); return (0); }