xref: /illumos-gate/usr/src/cmd/getent/dogethost.c (revision 581cede61ac9c14d8d4ea452562a567189eead78)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 #pragma ident	"%Z%%M%	%I%	%E% SMI"
23 
24 /*
25  * Copyright (c) 1994-2000 by Sun Microsystems, Inc.
26  * All rights reserved.
27  */
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <string.h>
36 #include <netdb.h>
37 #include "getent.h"
38 
39 static int
40 puthostent(const struct hostent *hp, FILE *fp)
41 {
42 	char **p;
43 	int rc = 0;
44 
45 	if (hp == NULL) {
46 		return (1);
47 	}
48 
49 	for (p = hp->h_addr_list; *p != 0; p++) {
50 		struct in_addr in;
51 		char **q;
52 
53 		(void) memcpy((char *)&in.s_addr, *p, sizeof (in));
54 		if (fprintf(fp, "%s\t%s",
55 			inet_ntoa(in), hp->h_name) == EOF)
56 			rc = 1;
57 		for (q = hp->h_aliases; *q != 0; q++) {
58 			if (fprintf(fp, " %s", *q) == EOF)
59 				rc = 1;
60 		}
61 		if (putc('\n', fp) == EOF)
62 			rc = 1;
63 	}
64 	return (rc);
65 }
66 
67 /*
68  * gethostbyname/addr - get entries from hosts database
69  */
70 int
71 dogethost(const char **list)
72 {
73 	struct hostent *hp;
74 	int rc = EXC_SUCCESS;
75 
76 	if (list == NULL || *list == NULL) {
77 		while ((hp = gethostent()) != NULL)
78 			(void) puthostent(hp, stdout);
79 	} else {
80 		for (; *list != NULL; list++) {
81 			struct in_addr addr;
82 			addr.s_addr = inet_addr(*list);
83 			if (addr.s_addr != (in_addr_t)-1)
84 				hp = gethostbyaddr((char *)&addr,
85 					sizeof (addr), AF_INET);
86 			else
87 				hp = gethostbyname(*list);
88 			if (hp == NULL)
89 				rc = EXC_NAME_NOT_FOUND;
90 			else
91 				(void) puthostent(hp, stdout);
92 		}
93 	}
94 
95 	return (rc);
96 }
97