#include <stdio.h>
#include <ctype.h>
#include <errno.h>

#include <sys/param.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/ioctl.h>

#include <net/bpf.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>

#include <string.h>

int main() {
  int fd;
  int n = 0;
  char device [sizeof "/dev/bpf000"];
  char iface[] = "ed0";
  char packet[1000]; int plen; char *p;
  struct ifreq ifr;
  struct bpf_version bv;
	      
	      
  /* liberally stolen from libpcap: */
     
   /*
    * Go through all the minors and find one that isn't in use.
    */
  do {
	(void)sprintf(device, "/dev/bpf%d", n++);
	fd = open(device, O_WRONLY);
  } while (fd < 0 && errno == EBUSY);
  
  if (fd < 0) {
	fprintf(stderr, "%s: %s\n", device, strerror(errno));
	return 1;
  }
  
  strcpy(ifr.ifr_name, iface);
  if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
    fprintf(stderr, "%s: %s\n", device, strerror(errno));
    return 1;
  }
  
  if (ioctl(fd, BIOCGBLEN, (caddr_t)&n) < 0) {
    errx("BIOCGBLEN");
  } else {
    printf("buffer is %d.\n", n);
  }

  /* Build packet here! */

  {
    struct ether_addr esrc, edst;
    struct ether_header ehead;
    struct ip iphead;
    struct tcphdr thead;

    p=packet;

    bcopy((char*)ether_aton("8:0:20:75:6c:8a"), &ehead.ether_shost,
	  sizeof(struct ether_addr));	/* should be granola */
    bcopy((char*)ether_aton("0:0:c:5:a2:33"), &ehead.ether_dhost,
	  sizeof(struct ether_addr));	/* w20rtr */
    ehead.ether_type = htons(ETHERTYPE_IP);
    fprintf(stdout, "From %s", ether_ntoa(ehead.ether_shost));
    fprintf(stdout, " to %s\n", ether_ntoa(ehead.ether_dhost));
    bcopy(&ehead, p, sizeof(ehead)); p+=sizeof(ehead);

/* IP */

    iphead.ip_hl=5;
    iphead.ip_v=4;
    iphead.ip_tos=0;
    iphead.ip_len=htons(54-14);	/* XXX */
    iphead.ip_id= htons(0x1234);
    iphead.ip_off=0;
    iphead.ip_ttl= 30;
    iphead.ip_p = IPPROTO_TCP;
    iphead.ip_sum = 0; /* XXX */
    if (inet_aton("18.70.0.228", &iphead.ip_dst) < 0)
      err("dst");
    if (inet_aton("18.70.0.25", &iphead.ip_src) < 0)
      err("src");

    bcopy(&iphead, p, sizeof(iphead)); p+=sizeof(iphead);

    *p++='A';
    *p++=0;

    plen=p-packet;
    printf("Packet length is %d.\n", plen);
  }

  if (write(fd, packet, plen) < 0) {
    fprintf(stderr, "write failed (%d): %s\n", errno, strerror(errno));
    return 1;
  }

  close(fd);

  return 0;
}
