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
|
#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];
#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 */
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 );
#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;
}
|