summaryrefslogtreecommitdiff
path: root/tests/port/test_getaddrinfo.c
blob: 24fc19bf132a87c049f696ae828ec9e999045820 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
    Copyright (C) 2008 Andreas Baumann <abaumann@yahoo.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#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( int argc, char **argv ) {
	struct addrinfo hints;
	struct addrinfo *result;
	struct addrinfo *res;
	int error;

	if( argc != 3 ) {
		fputs( "usage: test_getaddrinfo <host> <port>\n", stderr );
		exit( EXIT_FAILURE );
	}

#ifdef _WIN32
	WSADATA wsa_data;
	WSAStartup( MAKEWORD( 2, 2 ), &wsa_data );
#endif

	/* 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 */
	error = getaddrinfo( argv[1], argv[2], &hints, &result );
	if( error != 0 ) {
		fprintf( stderr, "getaddrinfo failed: %s (%d)\n",
			gai_strerror( error ), error );
#ifdef _WIN32
		WSACleanup( );
#endif
		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] = "";
		char service[NI_MAXSERV] = "";

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

		if( *hostname != '\0' ) {
			printf( "Got IP %s and port %s\n", hostname, service );
		}
	}
 
	freeaddrinfo( result );

#ifdef _WIN32
	WSACleanup( );
#endif
 
	return EXIT_SUCCESS;
}