Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active June 9, 2022 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st0le/492074968e2bc08e436580e1b7234db5 to your computer and use it in GitHub Desktop.
Save st0le/492074968e2bc08e436580e1b7234db5 to your computer and use it in GitHub Desktop.
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Usage: %s hostname\n", argv[0]);
exit(-1);
}
printf("GetHostByName results:\n");
// gethostbyname
struct hostent *hp = gethostbyname(argv[1]);
if (hp == NULL)
{
printf("gethostbyname() failed\n");
printf("%s: %d\n", hstrerror(h_errno), h_errno);
char buffer[500];
strerror_r(h_errno, buffer, 500);
printf("strerror_r: %s", buffer);
printf("\n");
}
else
{
printf("%s = ", hp->h_name);
unsigned int i=0;
while (hp->h_addr_list[i] != NULL)
{
printf("%s ", inet_ntoa(*(struct in_addr*)(hp->h_addr_list[i])));
i++;
}
printf("\n");
}
printf("GetAddrInfo results:\n");
// getaddrinfo
struct addrinfo *result, *rp, hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_flags = 0x02;
hints.ai_protocol = 0;
int s = getaddrinfo(argv[1], NULL, &hints, &result);
if (s != 0)
{
printf("getaddrinfo() failed\n");
printf("%s %d\n", gai_strerror(s), s);
char buffer[500];
strerror_r(h_errno, buffer, 500);
printf("strerror_r: %s", buffer);
printf("\n");
}
else
{
printf("%s = ", result->ai_canonname);
char str[INET6_ADDRSTRLEN];
for (rp = result; rp != NULL; rp = rp->ai_next)
{
inet_ntop(AF_INET6, rp->ai_addr->sa_data, str, INET6_ADDRSTRLEN);
printf("%s ", str);
}
}
printf("\n");
freeaddrinfo(result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment