Spostato il vecchi myhost.c e creato nuovo programma mygetaddr per provare
[gapil.git] / listati / mygetaddr.c
1     struct addrinfo hint;
2     struct addrinfo *res, *ptr;
3     int ret, port;
4     struct sockaddr_in *addr;
5     struct sockaddr_in6 *addr6;
6     char buffer[INET6_ADDRSTRLEN];
7     char *string;
8     ...
9     if ((argc - optind) != 2) {
10         printf("Wrong number of arguments %d\n", argc - optind);
11         usage();
12     }
13 /* main body */
14     ret = getaddrinfo(argv[1], argv[2], NULL, &res);
15     if (ret != 0) {
16         printf("Resolution error %s\n", gai_strerror(ret));
17         exit(1);
18     }
19     ptr = res;
20     printf("Canonical name %s\n", ptr->ai_canonname);
21     do {
22         if (ptr->ai_family == PF_INET) {
23             printf("IPv4 address: \n");
24             addr = (struct sockaddr_in *) ptr->ai_addr;
25             port = ntohs(addr->sin_port);
26             string = inet_ntop(addr->sin_family, &addr->sin_addr, 
27                                buffer, sizeof(buffer));
28         } else if (ptr->ai_family == PF_INET6) {
29             printf("IPv6 address: \n");
30             addr6 = (struct sockaddr_in *) ptr->ai_addr;
31             port = ntohs(addr6->sin6_port);
32             string = inet_ntop(addr6->sin6_family, &addr6->sin6_addr, 
33                                buffer, sizeof(buffer));
34         } else {
35             printf("Address family error\n");
36             exit(1);
37         }       
38         printf("\tIndirizzo %s\n", string);
39         printf("\tProtocollo %i\n", ptr->ai_protocol);
40         printf("\tPorta %i\n", port);
41         
42
43         ptr = ptr->ai_next;
44     } while (ptr != NULL);
45     exit(0);
46 }
47 /*
48  * routine to print usage info and exit
49  */
50 void usage(void) {
51     printf("Program mygethost: do an hostname resolution \n");
52     printf("Usage:\n");
53     printf("  mygethost [-h] hostname service\n");
54     printf("  -h   print this help\n");
55     exit(1);
56 }