Created
June 17, 2016 11:29
-
-
Save tiran/32eb2ab8265a31984bb5cf3cf468b72a to your computer and use it in GitHub Desktop.
glibc getaddrinfo() parsing with trailing data
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
#define _DEFAULT_SOURCE | |
#include <netdb.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.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, i; | |
char buf[NI_MAXHOST]; | |
hostname = "192.168.1.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, "80", &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) { | |
struct sockaddr_in in; | |
r = getnameinfo(rp->ai_addr, sizeof(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