acpi: moving flags_to_string to base code
[syslinux.git] / utils / gethostip.c
blobf3f87572fdb7dc7400e501674d9b44ee7ede3130
1 /* ----------------------------------------------------------------------- *
3 * Copyright 2001-2008 H. Peter Anvin - All Rights Reserved
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, Inc., 53 Temple Place Ste 330,
8 * Boston MA 02111-1307, USA; either version 2 of the License, or
9 * (at your option) any later version; incorporated herein by reference.
11 * ----------------------------------------------------------------------- */
14 * gethostip.c
16 * Small program to use gethostbyname() to print out a hostname in
17 * hex and/or dotted-quad notation
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <netdb.h>
23 #include <sys/socket.h>
24 #include <unistd.h>
25 #include <sysexits.h>
26 #define _GNU_SOURCE /* For getopt_long */
27 #include <getopt.h>
29 const struct option options[] = {
30 {"hexadecimal", 0, NULL, 'x'},
31 {"decimal", 0, NULL, 'd'},
32 {"dotted-quad", 0, NULL, 'd'},
33 {"full-output", 0, NULL, 'f'},
34 {"name", 0, NULL, 'n'},
35 {"help", 0, NULL, 'h'},
36 {NULL, 0, NULL, 0}
39 const char *program;
41 void usage(int exit_code)
43 fprintf(stderr, "Usage: %s [-dxnf] hostname/ip...\n", program);
44 exit(exit_code);
47 int main(int argc, char *argv[])
49 int opt;
50 int output = 0;
51 int i;
52 char *sep;
53 int err = 0;
55 struct hostent *host;
57 program = argv[0];
59 while ((opt = getopt_long(argc, argv, "dxfnh", options, NULL)) != -1) {
60 switch (opt) {
61 case 'd':
62 output |= 2; /* Decimal output */
63 break;
64 case 'x':
65 output |= 4; /* Hexadecimal output */
66 break;
67 case 'n':
68 output |= 1; /* Canonical name output */
69 break;
70 case 'f':
71 output = 7; /* Full output */
72 break;
73 case 'h':
74 usage(0);
75 break;
76 default:
77 usage(EX_USAGE);
78 break;
82 if (optind == argc)
83 usage(EX_USAGE);
85 if (output == 0)
86 output = 7; /* Default output */
88 for (i = optind; i < argc; i++) {
89 sep = "";
90 host = gethostbyname(argv[i]);
91 if (!host) {
92 herror(argv[i]);
93 err = 1;
94 continue;
97 if (host->h_addrtype != AF_INET || host->h_length != 4) {
98 fprintf(stderr, "%s: No IPv4 address associated with name\n",
99 argv[i]);
100 err = 1;
101 continue;
104 if (output & 1) {
105 printf("%s%s", sep, host->h_name);
106 sep = " ";
109 if (output & 2) {
110 printf("%s%u.%u.%u.%u", sep,
111 ((unsigned char *)host->h_addr)[0],
112 ((unsigned char *)host->h_addr)[1],
113 ((unsigned char *)host->h_addr)[2],
114 ((unsigned char *)host->h_addr)[3]);
115 sep = " ";
118 if (output & 4) {
119 printf("%s%02X%02X%02X%02X", sep,
120 ((unsigned char *)host->h_addr)[0],
121 ((unsigned char *)host->h_addr)[1],
122 ((unsigned char *)host->h_addr)[2],
123 ((unsigned char *)host->h_addr)[3]);
124 sep = " ";
127 putchar('\n');
130 return err;