summaryrefslogtreecommitdiff
path: root/tests/port/test_getaddrinfo.c
blob: b18d49d2dbccce7f320990bb328c024aad84c3c1 (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
54
55
56
57
58
59
60
61
62
#include "port/sys.h"

#define TEST_GETADDRINFO
#include "port/netdb.c"		/* 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 s[100];
		const struct sockaddr_in *addr_ipv4;
#ifdef HAVE_IPV6
		const struct sockaddr_in6 *addr_ipv6;
#endif

		memset( s, 0, 100 );
		switch( res->ai_family ) {
			case AF_INET:
				addr_ipv4 = (const struct sockaddr_in *)((void *)res->ai_addr);
				inet_ntop( res->ai_family, &addr_ipv4->sin_addr, s, 100 );
				break;

#ifdef HAVE_IPV6
			case AF_INET6:
				addr_ipv6 = (const struct sockaddr_in6 *)((void *)res->ai_addr);
				inet_ntop( res->ai_family, &addr_ipv6->sin6_addr, s, 100 );
				break;
#endif
		}

		printf( "%d %d %s\n", res->ai_family, res->ai_socktype, s );
	}
 
	freeaddrinfo( result );
 
	return EXIT_SUCCESS;
}