gai.c
changeset 0 760168a444e2
child 6 e54218f4b01c
equal deleted inserted replaced
-1:000000000000 0:760168a444e2
       
     1 #include <sys/types.h>
       
     2 #include <sys/socket.h>
       
     3 #include <netdb.h>
       
     4 #include <arpa/inet.h>
       
     5 
       
     6 #include <stdio.h>
       
     7 #include <stdlib.h>
       
     8 #include <string.h>
       
     9 
       
    10 int main(int argc, char **argv)
       
    11 {
       
    12     const char *node, *service, *proto;
       
    13     struct addrinfo *r, *results;
       
    14     struct addrinfo hints = { 0 };
       
    15     int e;
       
    16 
       
    17     if (argc < 2) {
       
    18 	fprintf(stderr, "Usage: %s hostname [service [protocol]]\n", argv[0]);
       
    19 	exit(1);
       
    20     }
       
    21 
       
    22     node = argc > 1 ? argv[1] : NULL;
       
    23     service = argc > 2 ? argv[2] : NULL;
       
    24     proto = argc > 3 ? argv[3] : NULL;
       
    25 
       
    26     hints.ai_socktype = proto == NULL ? 0
       
    27 	: strcmp(proto, "tcp") == 0 ? SOCK_STREAM
       
    28 	: strcmp(proto, "udp") == 0 ? SOCK_DGRAM
       
    29 	: 0;
       
    30 
       
    31     e = getaddrinfo(node, service, &hints, &results);
       
    32 
       
    33     if (e) {
       
    34 	fprintf(stderr, "%s: %s\n", argv[0], gai_strerror(e));
       
    35 	exit(3);
       
    36     }
       
    37 
       
    38 
       
    39     for (r = results; r != 0; r = r->ai_next) {
       
    40 	char host[1024];
       
    41 	char service[1024];
       
    42 	int e;
       
    43 	e = getnameinfo(r->ai_addr, r->ai_addrlen,
       
    44 	    host, sizeof(host),
       
    45 	    service, sizeof(service),
       
    46 	    NI_NUMERICHOST | NI_NUMERICSERV);
       
    47 
       
    48 	if (e) {
       
    49 	    fprintf(stderr, "getnameinfo: %s\n", gai_strerror(e));
       
    50 	    continue;
       
    51 	}
       
    52 
       
    53 	printf("%s, %s %d/%d\n", host, service, r->ai_socktype, r->ai_protocol);
       
    54     }
       
    55 
       
    56 
       
    57     return 0;
       
    58 
       
    59 }