// // Show the IP address // #include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netdb.h> #include<arpa/inet.h> #include<netinet/in.h>
intmain(int argc, charconst *argv[]) { int status = -1; structaddrinfohint; structaddrinfo *linkaddr, *temp; char ipstr[INET6_ADDRSTRLEN];
if (argc != 2) { printf("INPUT THE HOSTNAME\n"); return1; } // preprocess memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_UNSPEC; hint.ai_socktype = SOCK_STREAM; if ((status = getaddrinfo(argv[1], NULL, &hint, &linkaddr)) != 0) { printf("CANNOT GET ADDRESS INFO\n"); return1; } printf("IP addresses for %s:\n\n", argv[1]); // Select the ip addresses from the linked list for (temp = linkaddr; temp != NULL; temp = temp->ai_next) { void *address; char *ipVersion; // Get IP address itself // If it is IPv4 if(temp->ai_family == AF_INET) { // Use sockaddr_in to choose the ip address structsockaddr_in *sa_in = (struct sockaddr_in *)(temp->ai_addr); address = &(sa_in->sin_addr); ipVersion = "IPv4"; } else { struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)(temp->ai_addr); address = &(sa_in6->sin6_addr); ipVersion = "IPv6"; } // Binary mode to presentation inet_ntop(temp->ai_family,address,ipstr,sizeof(ipstr)); printf("%s: %s\n",ipVersion,ipstr); }