diff options
author | Daniel Friesel <derf@derf.homelinux.org> | 2009-08-09 11:30:42 +0200 |
---|---|---|
committer | Daniel Friesel <derf@derf.homelinux.org> | 2009-08-09 11:30:42 +0200 |
commit | 5666ded179caf3cddaee6a6d65ccc5c77b9e8d8f (patch) | |
tree | b2d6da3580b535329d2111099c5284e0d1c15052 /src | |
parent | e33f30a012de730926e49dd4b5c5d9c510d621be (diff) |
Added getopt (-4 / -6)
Diffstat (limited to 'src')
-rw-r--r-- | src/host.c | 33 |
1 files changed, 28 insertions, 5 deletions
@@ -6,6 +6,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> @@ -15,6 +16,13 @@ #define INPUT_IP 2 /** + * \brief Print some usage information + */ + +#define PRINT_USAGE \ + fprintf(stderr, "Usage: %s [-46] <hostname>\n", argv[0]) + +/** * \brief convert addrinfo to simple IP address * * \param address addrinfo struct containing the IP @@ -50,23 +58,38 @@ int main(int argc, char **argv) { char ip_address[INET6_ADDRSTRLEN]; int ret; int input_type = 0; + char option; - if (argc < 2) { - fprintf(stderr, "Usage: %s <hostname>\n", argv[0]); + while ((option = getopt(argc, argv, "46")) != -1) { + switch (option) { + case '4': + hints.ai_family = AF_INET; + break; + case '6': + hints.ai_family = AF_INET6; + break; + default: + PRINT_USAGE; + return EXIT_FAILURE; + } + } + + if (optind >= argc) { + PRINT_USAGE; return EXIT_FAILURE; } - ret = getaddrinfo(argv[1], NULL, &hints, &result); + ret = getaddrinfo(argv[optind], NULL, &hints, &result); if (ret != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); - exit(EXIT_FAILURE); + return EXIT_FAILURE; } for (address = result; address != NULL; address = address->ai_next) { if (addr_to_ip(address, ip_address, sizeof(ip_address)) == 0) continue; if (input_type == 0) { - if (strcmp(ip_address, argv[1]) == 0) + if (strcmp(ip_address, argv[optind]) == 0) input_type = INPUT_IP; else input_type = INPUT_HOST; |