Created
October 5, 2020 08:50
-
-
Save ssrlive/3d3867988141b99ba21dd8db492027c1 to your computer and use it in GitHub Desktop.
test getaddrinfo
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 <stdlib.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <stdio.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <assert.h> | |
#ifndef NI_MAXHOST | |
#define NI_MAXHOST 1025 | |
#endif | |
int main(int argc, char* argv[]) | |
{ | |
struct addrinfo* result; | |
struct addrinfo* res; | |
int error; | |
if (argc < 2) { | |
return -1; | |
} | |
/* resolve the domain name into a list of addresses */ | |
error = getaddrinfo(argv[1], NULL, NULL, &result); | |
if (error != 0) { | |
if (error == EAI_SYSTEM) { | |
perror("getaddrinfo"); | |
} else { | |
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error)); | |
} | |
exit(EXIT_FAILURE); | |
} | |
/* loop over all returned results and do inverse lookup */ | |
for (res = result; res != NULL; res = res->ai_next) { | |
char hostname[NI_MAXHOST] = { 0 }; | |
char _address[INET6_ADDRSTRLEN] = { 0 }; | |
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0); | |
if (error != 0) { | |
fprintf(stderr, "error in getnameinfo: %s\n", gai_strerror(error)); | |
continue; | |
} | |
if (res->ai_family == AF_INET) { | |
inet_ntop(res->ai_family, &((struct sockaddr_in*)res->ai_addr)->sin_addr, _address, sizeof(_address)); | |
} else if (res->ai_family == AF_INET6) { | |
inet_ntop(res->ai_family, &((struct sockaddr_in6*)res->ai_addr)->sin6_addr, _address, sizeof(_address)); | |
} else { | |
assert(0); | |
} | |
if (*hostname != '\0') { | |
printf("hostname: %s\t%s\n", hostname, _address); | |
} | |
} | |
freeaddrinfo(result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment