Last active
August 29, 2015 14:27
-
-
Save jackey/1dbb0587a12284905237 to your computer and use it in GitHub Desktop.
get hostname addresses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // ipshow.c | |
| // IPSHOW | |
| // | |
| // Created by Jackey Chen on 8/18/15. | |
| // Copyright (c) 2015 Jackey Chen. All rights reserved. | |
| // | |
| #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> | |
| int main(int argc, const char * argv[]) { | |
| struct addrinfo hints, *p, *res; | |
| char ipstr[INET6_ADDRSTRLEN]; | |
| if (argc != 2) { | |
| fprintf(stderr, "usage: SimpleC hostname \n"); | |
| return 1; | |
| } | |
| memset(&hints, 0, sizeof (hints)); | |
| hints.ai_family = AF_INET; | |
| hints.ai_socktype = SOCK_STREAM; | |
| int status; | |
| if (( status = getaddrinfo(argv[1], NULL, &hints, &res) ) != 0 ) { | |
| fprintf(stderr, "error: get %s ip address failed \n", argv[1]); | |
| return 1; | |
| } | |
| char *ipver; | |
| void *addr; | |
| for (p = res; p != NULL; p = p->ai_next) { | |
| if (p->ai_family == AF_INET) { | |
| ipver = "ipv4"; | |
| struct sockaddr_in *addrv4 = (struct sockaddr_in *) p->ai_addr; | |
| addr = &(addrv4->sin_addr); | |
| } | |
| else if (p->ai_family == AF_INET6) { | |
| ipver = "ipv6"; | |
| struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *) p->ai_addr; | |
| addr = &(addrv6->sin6_addr); | |
| } | |
| inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); | |
| printf("%s: %s \n", argv[1], ipstr); | |
| } | |
| freeaddrinfo(res); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment