Merge gpxe-for-syslinux
[syslinux.git] / gethostip.c
blob2a1e6e650178c1c5127f1715d1e714bc43811ad0
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[] =
31 { "hexadecimal", 0, NULL, 'x' },
32 { "decimal", 0, NULL, 'd' },
33 { "dotted-quad", 0, NULL, 'd' },
34 { "full-output", 0, NULL, 'f' },
35 { "name", 0, NULL, 'n' },
36 { "help", 0, NULL, 'h' },
37 { NULL, 0, NULL, 0 }
40 const char *program;
42 void usage(int exit_code)
44 fprintf(stderr, "Usage: %s [-dxnf] hostname/ip...\n", program);
45 exit(exit_code);
48 int main(int argc, char *argv[])
50 int opt;
51 int output = 0;
52 int i;
53 char *sep;
54 int err = 0;
56 struct hostent *host;
58 program = argv[0];
60 while ( (opt = getopt_long(argc, argv, "dxfnh", options, NULL)) != -1 ) {
61 switch ( opt ) {
62 case 'd':
63 output |= 2; /* Decimal output */
64 break;
65 case 'x':
66 output |= 4; /* Hexadecimal output */
67 break;
68 case 'n':
69 output |= 1; /* Canonical name output */
70 break;
71 case 'f':
72 output = 7; /* Full output */
73 break;
74 case 'h':
75 usage(0);
76 break;
77 default:
78 usage(EX_USAGE);
79 break;
83 if ( optind == argc )
84 usage(EX_USAGE);
86 if ( output == 0 )
87 output = 7; /* Default output */
89 for ( i = optind ; i < argc ; i++ ) {
90 sep = "";
91 host = gethostbyname(argv[i]);
92 if ( !host ) {
93 herror(argv[i]);
94 err = 1;
95 continue;
98 if ( host->h_addrtype != AF_INET || host->h_length != 4 ) {
99 fprintf(stderr, "%s: No IPv4 address associated with name\n", 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;