Last active
January 17, 2021 19:12
-
-
Save bsergean/7466e8a1d21da67c0dc9b992455c78a5 to your computer and use it in GitHub Desktop.
libuv dns example
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
// | |
// Adapted from https://github.com/Elzair/libuv-examples/blob/master/dns/dns.c | |
// to also loop through all results. | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <uv.h> | |
#include <string> | |
uv_loop_t *loop; | |
uv_buf_t alloc_buffer(uv_handle_t *handle, size_t suggested_size) { | |
return uv_buf_init((char*) malloc(suggested_size), suggested_size); | |
} | |
void on_resolved(uv_getaddrinfo_t *resolver, int status, struct addrinfo *res) { | |
if (status == -1) { | |
fprintf(stderr, "getaddrinfo callback error\n"); | |
return; | |
} | |
// iterate through the records to find a working peer | |
struct addrinfo* address; | |
for (address = res; address != nullptr; address = address->ai_next) | |
{ | |
char addr[17] = {'\0'}; | |
uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16); | |
fprintf(stderr, "%s\n", addr); | |
} | |
uv_freeaddrinfo(res); | |
} | |
int main() { | |
loop = uv_default_loop(); | |
struct addrinfo hints; | |
hints.ai_family = PF_INET; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_protocol = IPPROTO_TCP; | |
hints.ai_flags = 0; | |
std::string host("www.google.com"); | |
uv_getaddrinfo_t resolver; | |
fprintf(stderr, "%s is... ", host.c_str()); | |
int r = uv_getaddrinfo(loop, &resolver, on_resolved, host.c_str(), "80", &hints); | |
if (r) { | |
fprintf(stderr, "getaddrinfo call error\n"); | |
return 1; | |
} | |
return uv_run(loop, UV_RUN_DEFAULT); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment