#include #include #include #include #include #include #include #include #include #include // receiver listening port #define RCVR_PORT 4950 int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in rcvr_addr; struct hostent *he; int numbytes; if (argc != 3) { fprintf(stderr,"usage: talker hostname message\n"); exit(1); } // translates receiver name to address he = gethostbyname(argv[1]) ; if (he == NULL) { perror("gethostbyname"); exit(1); } // fills the receiver struct info rcvr_addr.sin_family = AF_INET; rcvr_addr.sin_port = htons(RCVR_PORT); rcvr_addr.sin_addr = *((struct in_addr *)he->h_addr); // zeroes the rest of the struct memset(&(rcvr_addr.sin_zero), '\0', 8); // creates the UDP socket sockfd = socket (AF_INET, SOCK_DGRAM, 0) ; if (sockfd == -1) { perror("socket"); exit(1); } // sends the message to the receiver using the socket numbytes = sendto (sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *) &rcvr_addr, sizeof(struct sockaddr)) ; if (numbytes == -1) { perror("sendto"); exit(1); } printf ("sent %d bytes to host %s port %d\n", numbytes, inet_ntoa (rcvr_addr.sin_addr), RCVR_PORT); // closes the socket close (sockfd); return 0; }