Created
December 4, 2014 00:51
-
-
Save jwasinger/1138af2e98c4488f9387 to your computer and use it in GitHub Desktop.
This file contains 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
int get_ip_from_hostname(char *host, char **output, int ip_v6) | |
{ | |
int error; | |
struct addrinfo hints, *res; | |
struct in_addr addr; | |
struct in6_addr addr6; | |
if(!host || !output) | |
{ | |
printf("bad argument 'host'\n"); | |
return -1; | |
} | |
*output = malloc(INET_ADDRSTRLEN); | |
if(!*output) | |
{ | |
error = errno; | |
printf("malloc error: %s\n", strerror(error)); | |
return -1; | |
} | |
memset(&hints, 0, sizeof(struct addrinfo)); | |
hints.ai_socktype = SOCK_STREAM; | |
if(ip_v6 != 0) | |
hints.ai_family = AF_INET6; | |
else | |
hints.ai_family = AF_INET; | |
hints.ai_flags = 0; | |
if((error = getaddrinfo(host, NULL, &hints, &res)) != 0) | |
{ | |
if(error == EAI_NONAME) | |
return 1; | |
printf("getaddrinfo error: %s", gai_strerror(error)); | |
return -1; | |
} | |
if(ip_v6 != 0) | |
addr6 = ((struct sockaddr_in *)(res->ai_addr)); | |
else | |
addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr; | |
if(ip_v6 != 0) | |
inet_ntop(AF_INET6, &addr6, *output, INET6_ADDRSTRLEN); | |
else | |
inet_ntop(AF_INET, &addr, *output, INET_ADDRSTRLEN); | |
freeaddrinfo(res); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment