xref: /illumos-gate/usr/src/cmd/getent/dogethost.c (revision 9164a50bf932130cbb5097a16f6986873ce0e6e5)
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 
23 /*
24  * Copyright (c) 1994-2000 by Sun Microsystems, Inc.
25  * All rights reserved.
26  */
27 
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <string.h>
35 #include <netdb.h>
36 #include "getent.h"
37 
38 static int
39 puthostent(const struct hostent *hp, FILE *fp)
40 {
41 	char **p;
42 	int rc = 0;
43 
44 	if (hp == NULL) {
45 		return (1);
46 	}
47 
48 	for (p = hp->h_addr_list; *p != 0; p++) {
49 		struct in_addr in;
50 		char **q;
51 
52 		(void) memcpy((char *)&in.s_addr, *p, sizeof (in));
53 		if (fprintf(fp, "%s\t%s",
54 			inet_ntoa(in), hp->h_name) == EOF)
55 			rc = 1;
56 		for (q = hp->h_aliases; *q != 0; q++) {
57 			if (fprintf(fp, " %s", *q) == EOF)
58 				rc = 1;
59 		}
60 		if (putc('\n', fp) == EOF)
61 			rc = 1;
62 	}
63 	return (rc);
64 }
65 
66 /*
67  * gethostbyname/addr - get entries from hosts database
68  */
69 int
70 dogethost(const char **list)
71 {
72 	struct hostent *hp;
73 	int rc = EXC_SUCCESS;
74 
75 	if (list == NULL || *list == NULL) {
76 		while ((hp = gethostent()) != NULL)
77 			(void) puthostent(hp, stdout);
78 	} else {
79 		for (; *list != NULL; list++) {
80 			struct in_addr addr;
81 			addr.s_addr = inet_addr(*list);
82 			if (addr.s_addr != (in_addr_t)-1)
83 				hp = gethostbyaddr((char *)&addr,
84 					sizeof (addr), AF_INET);
85 			else
86 				hp = gethostbyname(*list);
87 			if (hp == NULL)
88 				rc = EXC_NAME_NOT_FOUND;
89 			else
90 				(void) puthostent(hp, stdout);
91 		}
92 	}
93 
94 	return (rc);
95 }
96