Created
October 30, 2015 12:09
-
-
Save ximik777/ec821bd01e4756246721 to your computer and use it in GitHub Desktop.
static gethostbyname with libcares
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
#include <ares.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <stdarg.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include <unistd.h> | |
// gcc -static ares.c -lcares -o ares | |
static void state_cb(void *data, int s, int read, int write) { | |
printf("Change state fd %d read:%d write:%d\n", s, read, write); | |
} | |
static void callback(void *arg, int status, int timeouts, struct hostent *host) { | |
if (!host || status != ARES_SUCCESS) { | |
printf("Failed to lookup %s\n", ares_strerror(status)); | |
return; | |
} | |
char buff[INET_ADDRSTRLEN]; | |
inet_ntop(host->h_addrtype, host->h_addr_list[0], buff, sizeof(buff)); | |
memcpy(arg, buff, strlen(buff)); | |
} | |
static void wait_ares(ares_channel channel) { | |
for (; ;) { | |
struct timeval *tvp, tv; | |
fd_set read_fds, write_fds; | |
int nfds; | |
FD_ZERO(&read_fds); | |
FD_ZERO(&write_fds); | |
nfds = ares_fds(channel, &read_fds, &write_fds); | |
if (nfds == 0) { | |
break; | |
} | |
tvp = ares_timeout(channel, NULL, &tv); | |
select(nfds, &read_fds, &write_fds, NULL, tvp); | |
ares_process(channel, &read_fds, &write_fds); | |
} | |
} | |
int mygethostbyname(char *host, char *ip) { | |
ares_channel channel; | |
int status; | |
struct ares_options options; | |
int optmask = 0; | |
status = ares_library_init(ARES_LIB_INIT_ALL); | |
if (status != ARES_SUCCESS) { | |
printf("ares_library_init: %s\n", ares_strerror(status)); | |
return 0; | |
} | |
//options.sock_state_cb_data; | |
options.sock_state_cb = state_cb; | |
optmask |= ARES_OPT_SOCK_STATE_CB; | |
status = ares_init_options(&channel, &options, optmask); | |
if (status != ARES_SUCCESS) { | |
printf("ares_init_options: %s\n", ares_strerror(status)); | |
return 0; | |
} | |
ares_gethostbyname(channel, host, AF_INET, callback, ip); | |
wait_ares(channel); | |
ares_destroy(channel); | |
ares_library_cleanup(); | |
ip[strlen(ip)] = 0; | |
return 0; | |
} | |
int main() { | |
char *host = "google.com"; | |
char ip[16]; | |
getipbyhost(host, ip); | |
printf("IP [%s]\n", ip); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment