/* Datagram client, by Rahim Moledina */ # include # include # include # include # include # include #include #include #include # include // Send a datagram to a reciever whose name I get from the command line args. // The command line is dgramsend hotname portnumber int main (int argc, char *argv[]) { int sock,num=0; char symbol[50],curr_symbol[4]; char buf[1024]; char *tempstr; struct sockaddr_in name; struct hostent *hp; printf ("Please enter the ticker symbols of the Stocks: "); gets(symbol); // Getting stock symbol(s) from user sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("Opening datagram socket"); exit (1); // Datagram socket being opened } hp = gethostbyname(argv[1]); // Looking up the host name. if (hp == 0) { fprintf (stderr, "%s: unknown host\n", argv[1]); exit (2); // If host name not found, display error message. } bcopy(hp->h_addr, &name.sin_addr, hp->h_length); // Copying host address. name.sin_family = AF_INET; name.sin_port = htons(atoi(argv[2])); // Setting up address structure /* Send a message */ strcpy(curr_symbol,strtok(symbol," ")); if (sendto(sock,curr_symbol,sizeof(curr_symbol), 0, (sockaddr *)&name, sizeof(name)) < 0) perror("Sending datagram message"); // Send the current stock symbol. bzero (buf,sizeof(buf)); if (read(sock, buf, 1024) < 0) perror("Receiving datagram packet"); // If packet not recieved back output error. printf("\n%s\n",buf); while ((tempstr = strtok(NULL," ")) != NULL) { // While there are more stock symbols to send strcpy(curr_symbol,tempstr); if (sendto(sock,curr_symbol,sizeof(curr_symbol), 0, (sockaddr *)&name, sizeof(name)) < 0) perror("Sending datagram message"); // Send current stock symbol. bzero (buf,sizeof(buf)); if (read(sock, buf, 1024) < 0) perror("Receiving datagram packet"); // Display error if packet not recieved. printf("\n%s\n",buf); } close (sock); }