[comp.windows.x] xhosts.c --list, add, delete hosts your server talks to

dheller@cory.Berkeley.EDU (Dan Heller) (05/25/88)

I couldn't find a program to do this stuff for me, so I wrote it myself.
/*
 * xhosts -- list, add or remove hosts that your xserver will talk to.
 * Written by Dan Heller <island!argv@sun.com> May 24, 1988.
 *
 * cc -O -s xhosts.c -lX11 -o xhosts
 * Options:
 *    -a hostname    --adds "hostname" to the list of hosts.
 *    -r hostname    --removes "hostname" from the list of hosts.
 *
 * With no options, xhosts will list the names and IP addresses of
 * the hosts that your xserver will talk to.  See /etc/X?.hosts for
 * a list of hosts that were initialized when your xserver first
 * started up (? is the screen #).  This program can be used to
 * enable hosts that your server will accept connections from without
 * restarting the x server.  There is probably a program already in
 * existence that will do this, but I couldn't find one in the normal
 * distribution.  It was compiled and run on a sun3 running SunOS-3.5.
 */
#include <stdio.h>
#include <X11/Xlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>

main(c, argv)
char **argv;
{
    Display *dpy;
    char buf[64], *prog = *argv;
    XHostAddress *hosts, host;
    extern int XAddHost(), XRemoveHost();
    int nhosts, (*func)() = NULL;
    Bool enabled;
    struct hostent *h;

    /* We can talk to this display ONLY */
    if (!(dpy = XOpenDisplay("unix:0")))
	puts("can't talk to server"), exit(1);

    if (*++argv)
	if (!strcmp(*argv, "-a"))
	    func = XAddHost;
	else if (!strcmp(*argv, "-r"))
	    func = XRemoveHost;
	else if (**argv == '-' || !argv[1])
	    printf("usage: %s [-a | -r host [hosts ... ] ]\n", prog), exit(1);

    if (func)
	while (*++argv)
	    if (!(h = gethostbyname(*argv)))
		printf("%s: unknown host.\n", *argv);
	    else {
		printf("address: %s\n", inet_ntoa(*(u_long *)h->h_addr));
		host.address = h->h_addr;
		host.family = FamilyInternet;
		host.length = h->h_length;
		(*func)(dpy, &host);
	    }

    if (!(hosts = XListHosts(dpy, &nhosts, &enabled)))
	printf("Can't get host list from server.\n"), exit(1);

    printf("X server host access: %d hosts (%sabled)\n",
	nhosts, enabled? "en" : "dis");
    while (nhosts--) {
	(void) strcpy(buf, inet_ntoa(*(u_long *)hosts->address));
	if (!(h = gethostbyaddr(hosts->address, hosts->length, AF_INET)))
	    printf("can't find host from address: %s\n", buf);
	else
	    printf("%s (%s)\n", h->h_name, buf);
	hosts++;
    }
    exit(0);
}
Dan Heller	<island!argv@sun.com>