#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: stdhosts.c,v 1.20 2011/08/30 21:10:29 joerg Exp $");
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <err.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include "protos.h"
__dead static void usage(void);
int
main(int argc, char *argv[])
{
struct in_addr host_addr;
FILE *data_file;
size_t line_no;
size_t len;
char *line, *k, *v, *addr_string;
const char *fname;
int ch;
int af = 1 << 4;
struct addrinfo hints, *res;
addr_string = NULL;
while ((ch = getopt(argc, argv, "n")) != -1) {
switch (ch) {
case 'n':
af |= 1 << 6;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc > 1)
usage();
if (argc == 1) {
fname = argv[0];
data_file = fopen(fname, "r");
if (data_file == NULL)
err(1, "%s", fname);
} else {
fname = "<stdin>";
data_file = stdin;
}
line_no = 0;
for (;
(line = fparseln(data_file, &len, &line_no, NULL,
FPARSELN_UNESCALL));
free(line)) {
if (len == 0)
continue;
v = line;
for (k = v; *v && !isspace((unsigned char)*v); v++)
;
while (*v && isspace((unsigned char)*v))
*v++ = '\0';
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_NUMERICHOST;
if ((af & (1 << 4)) != 0 && inet_aton(k, &host_addr) == 1 &&
(addr_string = inet_ntoa(host_addr)) != NULL) {
printf("%s %s\n", addr_string, v);
} else if ((af & (1 << 6)) != 0 &&
getaddrinfo(k, "0", &hints, &res) == 0) {
freeaddrinfo(res);
printf("%s %s\n", k, v);
} else
warnx("%s line %lu: syntax error", fname,
(unsigned long)line_no);
}
exit(0);
}
static void
usage(void)
{
fprintf(stderr, "usage: %s [-n] [file]\n", getprogname());
exit(1);
}