Skip to content

Instantly share code, notes, and snippets.

@tiran
Last active January 31, 2016 13:38
Show Gist options
  • Save tiran/022745447d091b38c4ed to your computer and use it in GitHub Desktop.
Save tiran/022745447d091b38c4ed to your computer and use it in GitHub Desktop.
#define _DEFAULT_SOURCE
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
/*
$ gcc -o hostname hostname.c && ./hostname
gethostbyname: No address associated with name
getaddrinfo: 127.0.0.1
*/
int main(int argc, char *argv[])
{
char *hostname;
struct hostent *h;
struct addrinfo hints;
struct addrinfo *result, *rp;
int r;
char buf[NI_MAXHOST];
hostname = "127.0.0.1\r\nspam";
h = gethostbyname(hostname);
if (!h) {
const char *e;
e = hstrerror(h_errno);
printf("gethostbyname: %s\n", e);
} else {
printf("gethostbyname h_name: %s\n", h->h_name);
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = 0;
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
r = getaddrinfo(hostname, NULL, &hints, &result);
if (r != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(r));
exit(EXIT_FAILURE);
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
r = getnameinfo(rp->ai_addr, sizeof(struct sockaddr_in),
buf, sizeof(buf),
NULL, 0, NI_NUMERICHOST);
if (r != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(r));
exit(EXIT_FAILURE);
}
printf("getaddrinfo: %s\n", buf);
}
freeaddrinfo(result);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment