2. Write a simple UDP iterative server and client to convert a given DNS name (f
ID: 3629249 • Letter: 2
Question
2. Write a simple UDP iterative server and client to convert a given DNS name(for example, www.google.com) into its IP address(es). The client will read
the DNS name as a string from the user and send it to the server. The server
will convert it to one or more IP addresses and return it back to the client. The
client will then print ALL the addresses returned, and exit.
For basic UDP socket communication, see the sample program given. To get
the IP address corresponding to a DNS name, use the function
gethostbyname(). Look up the description of the function from the man
page and the tutorial on the webpage.
Explanation / Answer
#include #include #include #include #include #include #include #include #include #define MYPORT 53028 /* the port users will be sending to */ #define MAXBUFLEN 100 typedef char * string; int main(int argc, char *argv[]) { int sockfd,addr_len; struct sockaddr_in their_addr; struct hostent *he; int numbytes; /* client's address information */ if (argc != 3) { fprintf(stderr,"usage: talker hostname message "); exit(1); } if ((he=gethostbyname(argv[1])) == NULL) { herror("gethostbyname"); exit(1); } /* get the host info */ if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } their_addr.sin_family = AF_INET; their_addr.sin_port = htons(MYPORT); their_addr.sin_addr = *((struct in_addr *)he->h_addr); bzero(&(their_addr.sin_zero), 8); addr_len = sizeof(struct sockaddr); if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) { perror("sendto"); exit(1); } while(1) { char url[MAXBUFLEN]; printf(" Give the DNS Host Name: "); scanf("%s",url); //sending url sendto(sockfd, url, MAXBUFLEN, 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)); char ip_address[MAXBUFLEN]; char officialName[MAXBUFLEN]; recvfrom(sockfd, officialName, MAXBUFLEN, 0,(struct sockaddr *)&their_addr, &addr_len); printf("Official name is: "%s" ",officialName); printf("IP addresses: "); while(1) { if((numbytes=recvfrom(sockfd, ip_address, MAXBUFLEN, 0,(struct sockaddr *)&their_addr, &addr_len))==-1) { } else { if(strcmp(ip_address,"break")==0) break; printf("%s ",ip_address); } } } close(sockfd); return 0; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.