summaryrefslogtreecommitdiff
path: root/tests/port/test_getaddrinfo.c
blob: f163189c48a0bf0649331c0da3c993ac032cad55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "port/sys.h"

#include "port/netdb.h"		/* for getaddrinfo, NI_MAXHOST */

#include "port/stdlib.h"	/* for exit, EXIT_SUCCESS, itoa */
#include <stdio.h>		/* for fprintf */
#include <string.h>		/* for memset */

int main( void ) {
	struct addrinfo hints;
	struct addrinfo *result;
	struct addrinfo *res;
	int error;
	char port_or_service[10];

	/* tell getaddrinfo what we want */
	memset( &hints, 0, sizeof( struct addrinfo ) );
	hints.ai_flags = AI_PASSIVE;
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
 
	/* resolve the domain name into a list of addresses */
	itoa( 80, port_or_service, 10 );
	error = getaddrinfo( "www.yahoo.com", port_or_service, &hints, &result );
	if( error != 0 ) {
		fprintf( stderr, "getaddrinfo failed: %s (%d)\n",
			gai_strerror( error ), error );
		return EXIT_FAILURE;
	}
 
	/* loop over all returned results and do inverse lookup */
	for( res = result; res != NULL; res = res->ai_next ) {
		char hostname[NI_MAXHOST] = "";

		error = getnameinfo( res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST,
			NULL, 0,
			NI_NUMERICSERV | NI_NUMERICHOST );
		if( error != 0 ) {
			fprintf( stderr, "getnameinfo failed: %s (%d)\n",
				gai_strerror( error ), error );
			return EXIT_FAILURE;
		}

		if( *hostname != '\0' ) {
			printf( "%d %d %s\n", res->ai_family, res->ai_socktype, hostname );
		}
	}
 
	freeaddrinfo( result );
 
	return EXIT_SUCCESS;
}