/* $Header$
 *
 * Verify that an address is not in use (uses ARP)
 */

#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <sys/ioctl.h>
#include <net/nit.h>


int hex[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
	      0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	      0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };


main(argc, argv)
int	argc;
char	**argv;
{
    u_long  target;
    u_char  phys[6];
    int s, i;
    char	*ifc;
    struct sockaddr_nit snit;
    struct ether_arp pkt;
    struct ether_header *eh;
    struct sockaddr sa;

    if (argc < 3)
      usage(argv);
    if (argc == 4)
      ifc = argv[3];
    else
      ifc = "qe0";

    target = inet_addr(argv[1]);
    if (target == 0) {
	printf("invalid target IP address\n");
	exit(1);
    }

    if (strlen(argv[2]) != 12) {
	printf("use a 12-digit hex number for the physical address\n");
	exit(1);
    }
    for (i = 0; i < 6; i++) {
	phys[i] = (hex[argv[2][i*2]] << 4) | hex[argv[2][i*2+1]];
    }

    if ((s = socket(AF_NIT, SOCK_RAW, 0)) < 0) {
	perror("socket");
	exit(1);
    }
    snit.snit_family = AF_NIT;
    strncpy(snit.snit_ifname, ifc, NITIFSIZ);
    if (bind(s, &snit, sizeof(snit)) < 0) {
	perror("bind");
	exit(1);
    }
    pkt.arp_hrd = htons(ARPHRD_ETHER);
    pkt.arp_pro = htons(ETHERTYPE_IP);
    pkt.arp_hln = sizeof(struct ether_addr);
    pkt.arp_pln = sizeof(struct in_addr);
    pkt.arp_op = htons(ARPOP_REQUEST);
    for (i = 0; i < 6; i++)
      pkt.arp_sha[i] = phys[i];
    *(u_long *) &(pkt.arp_spa[0]) = target;
    *(u_long *) &(pkt.arp_tpa[0]) = 0L;
    sa.sa_family = AF_UNSPEC;
    eh = (struct ether_header *) &(sa.sa_data[0]);
    for (i = 0; i < 6; i++)
      eh->ether_dhost[i] = -1;
    eh->ether_type = ETHERTYPE_ARP;
    if (sendto(s, &pkt, sizeof(pkt), 0, &sa, sizeof(sa)) < 0) {
	perror("sendto");
	exit(1);
    }
    exit(0);
}


usage(argv)
char	**argv;
{
    fprintf(stderr, "Usage: %s target-ip-addr physical-ether-addr [interface]\n", argv[0]);
    exit(1);
}
