Completata la parte su getaddrinfo e rifatto il programma di esempio per
[gapil.git] / listati / mygetaddr.c
index 1499e2ba321b01766f20608b0929d6d63db626c4..2332b139f2bcf3d436d4044960c2f18b71aa7d00 100644 (file)
@@ -1,56 +1,37 @@
-    struct addrinfo hint;
-    struct addrinfo *res, *ptr;
-    int ret, port;
-    struct sockaddr_in *addr;
-    struct sockaddr_in6 *addr6;
-    char buffer[INET6_ADDRSTRLEN];
-    char *string;
-    ...
+    /* remaining argument check */
     if ((argc - optind) != 2) {
        printf("Wrong number of arguments %d\n", argc - optind);
         usage();
     }
-/* main body */
-    ret = getaddrinfo(argv[1], argv[2], NULL, &res);
+    /* main body */    
+    ret = getaddrinfo(argv[optind], argv[optind+1], &hint, &res); 
     if (ret != 0) {
        printf("Resolution error %s\n", gai_strerror(ret));
        exit(1);
     }
-    ptr = res;
-    printf("Canonical name %s\n", ptr->ai_canonname);
-    do {
-       if (ptr->ai_family == PF_INET) {
+    ptr = res;                                        /* init list pointer */
+    printf("Canonical name %s\n", ptr->ai_canonname); /* print cname */
+    while (ptr != NULL) {                             /* loop on list */
+       if (ptr->ai_family == PF_INET) {              /* if IPv4 */
            printf("IPv4 address: \n");
-           addr = (struct sockaddr_in *) ptr->ai_addr;
-           port = ntohs(addr->sin_port);
+           addr = (struct sockaddr_in *) ptr->ai_addr;     /* address */
+           port = ntohs(addr->sin_port);                   /* port */
            string = inet_ntop(addr->sin_family, &addr->sin_addr, 
                               buffer, sizeof(buffer));
-       } else if (ptr->ai_family == PF_INET6) {
+       } else if (ptr->ai_family == PF_INET6) {      /* if IPv6 */
            printf("IPv6 address: \n");
-           addr6 = (struct sockaddr_in *) ptr->ai_addr;
-           port = ntohs(addr6->sin6_port);
+           addr6 = (struct sockaddr_in *) ptr->ai_addr;    /* address */
+           port = ntohs(addr6->sin6_port);                 /* port */
            string = inet_ntop(addr6->sin6_family, &addr6->sin6_addr, 
                               buffer, sizeof(buffer));
-       } else {
+       } else {                                      /* else is an error */
            printf("Address family error\n");
            exit(1);
        }       
        printf("\tIndirizzo %s\n", string);
        printf("\tProtocollo %i\n", ptr->ai_protocol);
        printf("\tPorta %i\n", port);
-       
-
        ptr = ptr->ai_next;
-    } while (ptr != NULL);
+    }
     exit(0);
 }
-/*
- * routine to print usage info and exit
- */
-void usage(void) {
-    printf("Program mygethost: do an hostname resolution \n");
-    printf("Usage:\n");
-    printf("  mygethost [-h] hostname service\n");
-    printf("  -h   print this help\n");
-    exit(1);
-}