Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
	char *mode = argv[0];       /* Name of this binary, cc-mon or bw-mon? */
	char *dev = argv[1];			  /* The device to sniff on */
	char *filter_exp = argv[2];	/* The filter expression */
	
	char errbuf[PCAP_ERRBUF_SIZE];	/* Error string */
	struct bpf_program fp;			/* The compiled filter */
	pcap_t *handle;					    /* Session handle */
	bpf_u_int32 mask;				    /* Our netmask */
	bpf_u_int32 net;				    /* Our IP */
	struct pcap_pkthdr hdr;			/* The header that pcap gives us */
	const u_char *packet;			  /* The actual packet */
	pthread_t reporter; 			  /* timed reporting of measurements */
	
	if (argc < 3)
		usage(mode);
	
	// print given command, so that we can log everything by redirecting to a file
	printf("%s ",argv[0]);
	printf("%s ",argv[1]);
	printf("%s\n\n",argv[2]);
	
	// remove possible prepended paths
	mode += (strlen(mode) - strlen("cc-mon"));

	/* signal handler will close nfq hooks on exit */
	if(signal(SIGINT, sig_handler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);
	if(signal(SIGHUP, sig_handler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);
	if(signal(SIGTERM, sig_handler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);

	/* Find the properties for the device */
	if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
		fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
		net = 0;
		mask = 0;
	}
	/* Open the session, no promiscuous mode: they're our packets */
	handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
	if (handle == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
		return(2);
	}
	/* Compile and apply the filter */
	if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
		fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return(2);
	}
	if (pcap_setfilter(handle, &fp) == -1) {
		fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return(2);
	}

	/* init time spec */
	gettimeofday(&last_time, NULL);
	gettimeofday(&first_time, NULL);

	/* loop in chosen mode until sigint */
	if (0 == strcmp("bw-mon", mode)) {
		pthread_create(&reporter, NULL, reporter_thread, NULL);
		pcap_loop(handle, -1, throughput_cb, NULL);
	}
	else {
		pcap_loop(handle, -1, metadata_cb, NULL);
	}

	pcap_close(handle);

	exit(0);
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
	int ch;
	int debug = 0, promisc = 0;
	int timeout = 100; 
	bpf_u_int32 localnet=0, netmask=0;
	unsigned int error = 0;
	char *interface = NULL;
	char *proto = ETHER_TYPE_TEST;
	char in_string[MAXPROG];
	char tmp[ETHER_ADDR_LEN];
	char addr[ETHER_ADDR_LEN];
	char *user_addr = NULL;
	pcap_t *capture;
	struct bpf_program program;
	struct pcap_pkthdr *header;
	unsigned char *packet = NULL;

	while ((ch = getopt(argc, argv, "a:e:i:t:pd")) != -1) {
		switch (ch) {
		case 'a':
			user_addr = optarg;
			break;
		case 'e':
			proto = optarg;
			break;
		case 'i':
			interface = optarg;
			break;
		case 'p':
			promisc = 1;
			break;
		case 't':
			timeout = atoi(optarg);
			break;
		case 'd':
			debug = 1;
			break;
		case '?':
		default:
			usage("invalid arguments");
		}
	}
	argc -= optind;
	argv += optind;

	if (interface == NULL)
		usage("You must specify an interface");

	if (user_addr != NULL)
		ether_aton_r(user_addr, (struct ether_addr *)&tmp);

	if ((capture = pcap_open_live(interface, SNAPLEN, promisc, timeout, 
				      &errbuf[0])) == NULL)
		usage(errbuf);

	snprintf(&in_string[0], MAXPROG, "ether proto %s\n", proto);

	if (pcap_lookupnet(interface, &localnet, &netmask, errbuf) < 0)
		usage(errbuf);

	if (pcap_compile(capture, &program, in_string, 1, netmask) < 0)
		usage(errbuf);

	if (pcap_setfilter(capture, &program) < 0)
		usage(errbuf);

	if (pcap_setdirection(capture, PCAP_D_IN) < 0)
		usage(errbuf);

	while (1) {
		error = pcap_next_ex(capture, &header, 
				     (const unsigned char **)&packet);
		if (error == 0)
			continue;
		if (error == -1)
			usage("packet read error");
		if (error == -2)
			usage("savefile?  invalid!");

		if (debug) {
			printf ("got packet of %d length\n", header->len);
			printf ("header %s\n", 
				ether_ntoa((const struct ether_addr*)
					   &packet[0]));
			printf ("header %s\n", 
				ether_ntoa((const struct ether_addr*)
					   &packet[ETHER_ADDR_LEN]));
		}
		
		/*
		 * If the user did not supply an address then we simply
		 * reverse the source and destination addresses.
		 */
		if (user_addr == NULL) {
			bcopy(packet, &tmp, ETHER_ADDR_LEN);
			bcopy(&packet[ETHER_ADDR_LEN], packet, ETHER_ADDR_LEN);
			bcopy(&tmp, &packet[ETHER_ADDR_LEN], ETHER_ADDR_LEN);
		} else {
			bcopy(&tmp, packet, ETHER_ADDR_LEN);
		}
		if (pcap_inject(capture, packet, header->len) < 0)
			if (debug)
				pcap_perror(capture, "pcap_inject");
	}
}
Ejemplo n.º 3
0
int main(int argc, char **argv){
  /* using device name */
  char *device_name;

  /* pcap error message buffer */
  char ebuf[PCAP_ERRBUF_SIZE];

  /* pcap_compile */
  char *cmdbuf;
  int Oflag = 1;
  struct bpf_program fcode;
  bpf_u_int32 localnet, netmask; 

  int timeout = 1000;


  if(set_sighdl() < 0){
    perror("set signal handler(SIGINT):");
    exit(1);
  }

  if(!get_option(argc, argv)){
    printf("Syntax Error...\n");
    printf("Usage:goblin [-i interface] [-c \"condition\"] [-m rst/tail] [-t n(msec)]\n");
    exit(1);
  }

  sum_packet = 0;
  sum_ack = 0;
  sum_syn = 0;


  if((mode = set_mode(argv)) == 0){
    printf("Undefined Mode (\"rst\" or \"tail\")\n");
    exit(1);
  }

  if((timeout = set_timeout(mode,argv)) == 0){
    printf("Illigal Time  < 0\n");
    exit(1);
  }
	   
  init_socks();
  
  if(option.i != 0){
    device_name = (char*)malloc( (strlen(argv[option.i]) + 1) * sizeof(char) );
    strcpy(device_name,argv[option.i]);
  }
  else{
    if((device_name = pcap_lookupdev(ebuf)) == NULL){
      fprintf(stderr,"%s\n",ebuf);
      exit(1);
    }
  }

  printf("PROMISC DEV: %s\n",device_name);
  //  pd = pcap_open_live(device_name, DEFAULT_LEN, 1, 1000, ebuf);
  pd = pcap_open_live(device_name, ETHER_MAX_LEN, 1, timeout, ebuf);
  if(option.i != 0) free(device_name);

  if(pd == NULL){
    fprintf(stderr,"%s\n",ebuf);
    exit(1);
  }

  if (pcap_lookupnet(device_name, &localnet, &netmask, ebuf) < 0) {
    localnet = 0;
    netmask = 0;
    fprintf(stderr,"%s", ebuf);
    exit(1);
  }

  if(option.c != 0){
    cmdbuf = argv[option.c];
    if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0){
      fprintf(stderr,"%s", pcap_geterr(pd));
      exit(1);
    }
    if (pcap_setfilter(pd, &fcode) < 0){
      fprintf(stderr,"%s", pcap_geterr(pd));
      exit(1);
    }
  }


  switch(mode){
  case 't':
    if( pcap_loop(pd, -1, capture_packet, NULL) < 0 ){
      fprintf(stdout,"pcap_loop:%s\n",pcap_geterr(pd));
      exit(1);
    }
    break;

  case 'r':
    if( pcap_loop(pd, -1, discriminate_packet, NULL) < 0 ){
      fprintf(stdout,"pcap_loop:%s\n",pcap_geterr(pd));
      exit(1);
    }
    break;
  }

  return 0;
}
Ejemplo n.º 4
0
int main()
{
	pcap_if_t *alldevs;			// 디바이스 목록 리스트
	pcap_if_t *d;				// 선택한 디바이스
	int choice;					// 디바이스 선택 번호
	int i = 0;
	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	//필터룰 지정   
	char *filter = "port 80";
	struct bpf_program fcode;
	bpf_u_int32 NetMask;
	// 디바이스 리스트 가져옴
	if (pcap_findalldevs(&alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	// 디바이스 리스트 출력
	for (d = alldevs; d; d = d->next)
	{
		printf("%d. %s", ++i, d->name);
		if (d->description)
			printf(" (%s)\n", d->description);
		else
			printf(" (No description available)\n");		// 디바이스 출력 오류
	}

	// 디바이스 리스트 없을 시 
	if (i == 0)
	{
		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
		return -1;
	}

	// 디바이스 선택
	printf("Enter the interface number (1-%d):", i);
	scanf("%d", &choice);

	// 이상한 값을 넣었나 안넣었나
	if (choice < 1 || choice > i)
	{
		printf("\nInterface number out of range.\n");
		// 반환
		pcap_freealldevs(alldevs);
		return -1;
	}

	// 선택한 장치로
	for (d = alldevs, i = 0; i< choice - 1; d = d->next, i++);

	// 네트워크 디바이스 오픈
	if ((adhandle = pcap_open_live(d->name, 65536, 1, 1000, errbuf)) == NULL)		// 패킷 받을 준비
	{
		fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		// 반환
		pcap_freealldevs(alldevs);
		return -1;
	}

	printf("\nlistening on %s...\n", d->description);

	NetMask = 0xffffff;						// 255.255.255.0
	if (pcap_compile(adhandle, &fcode, filter, 1, NetMask) < 0)			// 받은 패킷들 필터 적용....
	{																	// 정확히는 잘 모르겠다.
		fprintf(stderr, "\nError compiling filter: wrong syntax.\n");
		pcap_close(adhandle);
		return -3;
	}
	// 사용자가 정의한 필터룰 적용  
	if (pcap_setfilter(adhandle, &fcode)<0)								// 컴파일 된 패킷들을 핸들에 적용시켜줌
	{
		fprintf(stderr, "\nError setting the filter\n");
		pcap_close(adhandle);
		return -4;
	}
	/* 장치 목록 해제 */
	pcap_freealldevs(alldevs);
	/* 캡처 시작 */
	while (1)
	{
		pcap_loop(adhandle, 1, packet_ethernet_handler, NULL);		// ethernet 헤더 뽑기
		pcap_loop(adhandle, 1, packet_ip_handler, NULL);			// TCPIP 헤더 뽑기
		pcap_loop(adhandle, 1, packet_tcp_handler, NULL);		// TCP 헤더 뽑기
	}
	pcap_close(adhandle);    // 네트워크 디바이스 핸들 종료  
	return 0;
}
int main(int argc, char *argv[])
{
  pcap_t *handle;                 /* Session handle */
  const char *dev;                /* The device to sniff on */
  char errbuf[PCAP_ERRBUF_SIZE];  /* Error string */
  struct bpf_program fp;          /* The compiled filter */
  const char *filter_exp;         /* The filter expression */
  bpf_u_int32 mask;               /* Our netmask */
  bpf_u_int32 net;                /* Our IP */
  struct pcap_pkthdr header;      /* The header that pcap gives us */
  const u_char *packet;           /* The actual packet */
  int capture_duration;           /* How long to capture in seconds */
  time_t begin_time;              /* Capture begin time */
  unsigned long total_bytes = 0;  /* Total bytes seen in packets */

  if (argc != 4) {
    fprintf(stderr,
            "Usage: %s <device> <capture duration> <filter expression>\n",
            argv[0]);
    return(1);
  }

  dev = argv[1];
  capture_duration = atoi(argv[2]);
  filter_exp = argv[3];

  /* Find the properties for the device */
  if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
      fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
    net = 0;
    mask = 0;
  }

  /* Open the session in non-promiscuous mode */
  handle = pcap_open_live(dev, BUFSIZ, 0, 1000, errbuf);
  if (handle == NULL) {
      fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
    return(2);
  }

  /* Compile and apply the filter */
  if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
      fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp,
              pcap_geterr(handle));
    return(2);
  }

  if (pcap_setfilter(handle, &fp) == -1) {
      fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp,
              pcap_geterr(handle));
    return(2);
  }

  begin_time = time(NULL);
  while (time(NULL) - begin_time < capture_duration) {
    /* Grab a packet and record its length */
    packet = pcap_next(handle, &header);
    total_bytes += header.len;
  }

  printf("Total bytes: %.2f MB\n", (float)total_bytes / 1024 / 1024);

  /* And close the session */
  pcap_close(handle);
  return(0);
}
int main_pcap()
{

	char *dev = NULL;			/* capture device name */
	char errbuf[PCAP_ERRBUF_SIZE];		/* error buffer */
	pcap_t *handle;				/* packet capture handle */

	char filter_exp[] = "ip";		/* filter expression [3] */
	struct bpf_program fp;			/* compiled filter program (expression) */
	bpf_u_int32 mask;			/* subnet mask */
	bpf_u_int32 net;			/* ip */
	int num_packets = 1;			/* number of packets to capture */

	 /*find a capture device if not specified on command-line */
	dev = pcap_lookupdev(errbuf);
	if (dev == NULL) {
		fprintf(stderr, "Couldn't find default device: %s\n",
		    errbuf);
		exit(EXIT_FAILURE);
	}
	//}
	
	/* get network number and mask associated with capture device */
	if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
		fprintf(stderr, "Couldn't get netmask for device %s: %s\n",
		    dev, errbuf);
		net = 0;
		mask = 0;
	}

	/* print capture info */
	printf("Device: %s\n", dev);
	printf("Number of packets: %d\n", num_packets);
	printf("Filter expression: %s\n", filter_exp);

	/* open capture device */
	handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
	if (handle == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
		exit(EXIT_FAILURE);
	}

	/* make sure we're capturing on an Ethernet device [2] */
	if (pcap_datalink(handle) != DLT_EN10MB) {
		fprintf(stderr, "%s is not an Ethernet\n", dev);
		exit(EXIT_FAILURE);
	}

	/* compile the filter expression */
	if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
		fprintf(stderr, "Couldn't parse filter %s: %s\n",
		    filter_exp, pcap_geterr(handle));
		exit(EXIT_FAILURE);
	}

	/* apply the compiled filter */
	if (pcap_setfilter(handle, &fp) == -1) {
		fprintf(stderr, "Couldn't install filter %s: %s\n",
		    filter_exp, pcap_geterr(handle));
		exit(EXIT_FAILURE);
	}

	/* now we can set our callback function */
	pcap_loop(handle, num_packets, got_packet, NULL);

	/* cleanup */
	pcap_freecode(&fp);
	pcap_close(handle);

	printf("\nCapture complete.\n");

return 0;
}
Ejemplo n.º 7
0
int
init_pcap(void)
{
	struct bpf_program	bpfp;
	char	filter[PCAPFSIZ] = "ip and port 25 and action pass "
		    "and tcp[13]&0x12=0x2";

#ifdef __FreeBSD__
	if(!use_pf) {
		strncpy(filter, "ip and port 25 and tcp[13]&0x12=0x2", sizeof(filter));
	}
#endif

	if ((hpcap = pcap_open_live(pflogif, PCAPSNAP, 1, PCAPTIMO,
	    errbuf)) == NULL) {
		logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
		return (-1);
	}

#ifndef __FreeBSD__
	if (pcap_datalink(hpcap) != DLT_PFLOG) {
#else
	if ((use_pf && pcap_datalink(hpcap) != DLT_PFLOG) || (!use_pf && pcap_datalink(hpcap)!=DLT_NULL)) {
#endif
		logmsg(LOG_ERR, "Invalid datalink type");
		pcap_close(hpcap);
		hpcap = NULL;
		return (-1);
	}

	if (networkif != NULL) {
		strlcat(filter, " and on ", PCAPFSIZ);
		strlcat(filter, networkif, PCAPFSIZ);
	}

	if (pcap_compile(hpcap, &bpfp, filter, PCAPOPTZ, 0) == -1 ||
	    pcap_setfilter(hpcap, &bpfp) == -1) {
		logmsg(LOG_ERR, "%s", pcap_geterr(hpcap));
		return (-1);
	}

	pcap_freecode(&bpfp);

	if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
		logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
		return (-1);
	}

	return (0);
}

/* ARGSUSED */
void
logpkt_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
{
	sa_family_t		 af;
	u_int8_t		 hdrlen;
	u_int32_t		 caplen = h->caplen;
	const struct ip		*ip = NULL;
	const struct pfloghdr	*hdr;
	char			 ipstraddr[40] = { '\0' };
	uint8_t link_offset;

	hdr = (const struct pfloghdr *)sp;
	if(use_pf){
		if (hdr->length < MIN_PFLOG_HDRLEN) {
			logmsg(LOG_WARNING, "invalid pflog header length (%u/%u). "
			"packet dropped.", hdr->length, MIN_PFLOG_HDRLEN);
			return;
		}

		hdrlen = BPF_WORDALIGN(hdr->length);

		if (caplen < hdrlen) {
			logmsg(LOG_WARNING, "pflog header larger than caplen (%u/%u). "
			"packet dropped.", hdrlen, caplen);
			return;
		}

		/* We're interested in passed packets */
		if (hdr->action != PF_PASS)
			return;

		af = hdr->af;
		if (af == AF_INET) {
			ip = (const struct ip *)(sp + hdrlen);
			if (hdr->dir == PF_IN)
				inet_ntop(af, &ip->ip_src, ipstraddr,
			sizeof(ipstraddr));
			else if (hdr->dir == PF_OUT && !flag_inbound)
				inet_ntop(af, &ip->ip_dst, ipstraddr,
			sizeof(ipstraddr));
		}
	}
	else { /* IPFW code */
		link_offset = 4; /* LOOPHDR_SIZE */
		struct ip      *ip4_pkt = (struct ip *)    (sp + link_offset);
		if(ip4_pkt->ip_v!=4){
			logmsg(LOG_WARNING, "Incorrect IP version: %d", ip4_pkt->ip_v);
			return;
		}
		inet_ntop(AF_INET, (const void *)&ip4_pkt->ip_src, ipstraddr, sizeof(ipstraddr));
	}

	if (ipstraddr[0] != '\0') {
		if (!use_pf || hdr->dir == PF_IN)
			logmsg(LOG_DEBUG,"inbound %s", ipstraddr);
		else
			logmsg(LOG_DEBUG,"outbound %s", ipstraddr);
		dbupdate(PATH_SPAMD_DB, ipstraddr);
	}
}
Ejemplo n.º 8
0
static struct pcap* open_src_live(const char* iface){
	return pcap_open_live(iface, BUFSIZ, 1, 1000, errorBuffer);
}
Ejemplo n.º 9
0
pcap_t *
pcap_create(const char *source, char *errbuf)
{
	D("src %s (call open liveted)", source);
	return pcap_open_live(source, 0, 1, 100, errbuf);
}
Ejemplo n.º 10
0
int main ( int argc , char *argv[] )
{
	/* parameters parsing */
	int c;

	/* pcap */
	char 			errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program 	fp;
	char 			filter_exp[] = "ip and tcp";
	char 			*source = 0;
	char 			*filter = filter_exp;
	const unsigned char	*packet = 0;
	struct pcap_pkthdr 	header;

	/* packet dissection */
	struct ip	*ip;
	unsigned int	error;

	/* extra */
	unsigned int ipf,tcps;

	fprintf( stderr, "\n###########################" );
	fprintf( stderr, "\n#     libntoh Example     #" );
	fprintf( stderr, "\n# ----------------------- #" );
	fprintf( stderr, "\n# Written by Chema Garcia #" );
	fprintf( stderr, "\n# ----------------------- #" );
	fprintf( stderr, "\n#  http://safetybits.net  #" );
	fprintf( stderr, "\n#   [email protected]  #" );
	fprintf( stderr, "\n###########################\n" );

	fprintf( stderr, "\n[i] libntoh version: %s\n", ntoh_version() );

	if ( argc < 3 )
	{
		fprintf( stderr, "\n[+] Usage: %s <options>\n", argv[0] );
		fprintf( stderr, "\n+ Options:" );
		fprintf( stderr, "\n\t-i | --iface <val> -----> Interface to read packets from" );
		fprintf( stderr, "\n\t-f | --file <val> ------> File path to read packets from" );
		fprintf( stderr, "\n\t-F | --filter <val> ----> Capture filter (default: \"ip and tcp\")" );
		fprintf( stderr, "\n\t-c | --client ----------> Receive client data");
		fprintf( stderr, "\n\t-s | --server ----------> Receive server data\n\n");
		exit( 1 );
	}

	/* check parameters */
	while ( 1 )
	{
		int option_index = 0;
		static struct option long_options[] =
		{
		{ "iface" , 1 , 0 , 'i' } ,
		{ "file" , 1 , 0 , 'f' } ,
		{ "filter" , 1 , 0 , 'F' } ,
		{ "client" , 0 , 0 , 'c' },
		{ "server" , 0 , 0 , 's' },
		{ 0 , 0 , 0 , 0 } };

		if ( ( c = getopt_long( argc, argv, "i:f:F:cs", long_options, &option_index ) ) < 0 )
			break;

		switch ( c )
		{
			case 'i':
				source = optarg;
				handle = pcap_open_live( optarg, 65535, 1, 0, errbuf );
				break;

			case 'f':
				source = optarg;
				handle = pcap_open_offline( optarg, errbuf );
				break;

			case 'F':
				filter = optarg;
				break;

			case 'c':
				receive |= RECV_CLIENT;
				break;

			case 's':
				receive |= RECV_SERVER;
				break;
		}
	}

	if ( !receive )
		receive = (RECV_CLIENT | RECV_SERVER);

	if ( !handle )
	{
		fprintf( stderr, "\n[e] Error loading %s: %s\n", source, errbuf );
		exit( -1 );
	}

	if ( pcap_compile( handle, &fp, filter, 0, 0 ) < 0 )
	{
		fprintf( stderr, "\n[e] Error compiling filter \"%s\": %s\n\n", filter, pcap_geterr( handle ) );
		pcap_close( handle );
		exit( -2 );
	}

	if ( pcap_setfilter( handle, &fp ) < 0 )
	{
		fprintf( stderr, "\n[e] Cannot set filter \"%s\": %s\n\n", filter, pcap_geterr( handle ) );
		pcap_close( handle );
		exit( -3 );
	}
	pcap_freecode( &fp );

	/* verify datalink */
	if ( pcap_datalink( handle ) != DLT_EN10MB )
	{
		fprintf ( stderr , "\n[e] libntoh is independent from link layer, but this example only works with ethernet link layer\n");
		pcap_close ( handle );
		exit ( -4 );
	}

	fprintf( stderr, "\n[i] Source: %s / %s", source, pcap_datalink_val_to_description( pcap_datalink( handle ) ) );
	fprintf( stderr, "\n[i] Filter: %s", filter );

	fprintf( stderr, "\n[i] Receive data from client: ");
	if ( receive & RECV_CLIENT )
		fprintf( stderr , "Yes");
	else
		fprintf( stderr , "No");

	fprintf( stderr, "\n[i] Receive data from server: ");
	if ( receive & RECV_SERVER )
		fprintf( stderr , "Yes");
	else
		fprintf( stderr , "No");

	signal( SIGINT, &shandler );
	signal( SIGTERM, &shandler );

	/*******************************************/
	/** libntoh initialization process starts **/
	/*******************************************/

	ntoh_init ();

	if ( ! (tcp_session = ntoh_tcp_new_session ( 0 , 0 , &error ) ) )
	{
		fprintf ( stderr , "\n[e] Error %d creating TCP session: %s" , error , ntoh_get_errdesc ( error ) );
		exit ( -5 );
	}

	fprintf ( stderr , "\n[i] Max. TCP streams allowed: %d" , ntoh_tcp_get_size ( tcp_session ) );

	if ( ! (ipv4_session = ntoh_ipv4_new_session ( 0 , 0 , &error )) )
	{
		ntoh_tcp_free_session ( tcp_session );
		fprintf ( stderr , "\n[e] Error %d creating IPv4 session: %s" , error , ntoh_get_errdesc ( error ) );
		exit ( -6 );
	}

	fprintf ( stderr , "\n[i] Max. IPv4 flows allowed: %d\n\n" , ntoh_ipv4_get_size ( ipv4_session ) );

	/* capture starts */
	while ( ( packet = pcap_next( handle, &header ) ) != 0 )
	{
		/* get packet headers */
		ip = (struct ip*) ( packet + sizeof ( struct ether_header ) );
		if ( (ip->ip_hl * 4 ) < sizeof(struct ip) )
			continue;

		/* it is an IPv4 fragment */
		if ( NTOH_IPV4_IS_FRAGMENT(ip->ip_off) )
			send_ipv4_fragment ( ip , &ipv4_callback );
		/* or a TCP segment */
		else if ( ip->ip_p == IPPROTO_TCP )
			send_tcp_segment ( ip , &tcp_callback );
	}

	tcps = ntoh_tcp_count_streams( tcp_session );
	ipf = ntoh_ipv4_count_flows ( ipv4_session );

	/* no streams left */
	if ( ipf + tcps > 0 )
	{
		fprintf( stderr, "\n\n[+] There are currently %i stored TCP stream(s) and %i IPv4 flow(s). You can wait them to get closed or press CTRL+C\n" , tcps , ipf );
		pause();
	}

	shandler( 0 );

	//dummy return
	return 0;
}
Ejemplo n.º 11
0
void ICMPSniffer::run()
{
    char dev[DEV_MAX] ;			/* set device name */
    strcpy(dev,global_dev);
    char errbuf[PCAP_ERRBUF_SIZE];		/* error buffer */
    /* find a capture device if not specified by dev */
    //dev = pcap_lookupdev(errbuf);
    if (dev == NULL)
        return;

    /* get network number and mask associated with capture device */
    bpf_u_int32 mask;			/* subnet mask */
    bpf_u_int32 net;			/* ip */
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
        return;

    /* open capture device */
    pcap_t *handle;				/* packet capture handle */
    handle = pcap_open_live(dev, SNAP_LEN, 0, 1000, errbuf); // needn't to be promiscuous
    if (handle == NULL)
        return;

    /* make sure we're capturing on an Ethernet device [2] */
    if (pcap_datalink(handle) != DLT_EN10MB)
        return;

    /* compile the filter expression */
    struct bpf_program fp;			/* compiled filter program (expression) */
    char filter_exp[] = "icmp";
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1)
        return;

    /* apply the compiled filter */
    if (pcap_setfilter(handle, &fp) == -1)
        return;

    /* now we can start capturing packets */
    struct pcap_pkthdr header;	/* The header that pcap gives us */
    //const struct libnet_ethernet_hdr *ethernet; /* The ethernet header */
    const struct libnet_ipv4_hdr *ip; /* The IP header */
    const struct libnet_icmpv4_hdr *icmp; /* The ICMP header */
    const u_char *packet;   // the actual packet we picked
    u_int size_ip;
    while(!m_stop){
        packet = pcap_next(handle,&header);
        if( NULL==packet )
            continue;
        //ethernet = (struct libnet_ethernet_hdr*)(packet);
        ip = (struct libnet_ipv4_hdr*)(packet + LIBNET_ETH_H);
        size_ip = IP_SIZE(ip);
        icmp = (struct libnet_icmpv4_hdr*)(packet + LIBNET_ETH_H + size_ip);
        unsigned int ipSource = ip->ip_src.s_addr;
        //unsigned short ipID = ntohs(ip->ip_id);
        unsigned short icmpID = ntohs(icmp->hun.echo.id);
        // check whether the packet is corresponding to our sender
        QList<IPID_Info>::iterator start=m_info.begin(), last=m_info.end();
        while(start!=last){
            // check if the response is corresponding to my ping
            if((*start).ip==ipSource && //(*start).IPid==ipID && //!!!!!!!!!!!!! sina don't reply the same!
                    (*start).ICMPid==icmpID){
                emit pingFounded(ipSource,0,PROTOCOL_ICMP);
                m_info.erase(start);    // to avoid the duplicate table row same icmp response
                break;
            }
            ++start;
        }
    }

    /* cleanup */
    pcap_freecode(&fp);
    pcap_close(handle);

    return;
}
Ejemplo n.º 12
0
int passive_main(int argc, char *argv[])
{
	register int c, i;             /* Temporary variable   */
	bpf_u_int32 mask;              /* our netmask          */
	bpf_u_int32  net;              /* our IP adx           */
	uint32_t     npolls;           /* Number of pcap polls */
	char errbuf[PCAP_ERRBUF_SIZE]; /* pcap error buffer    */
	char *filter = NULL;           /* pcap filter          */
	pcap_t *handle;	               /* pcap handle          */
	struct bpf_program program;    /* BPF filter program   */

	npolls = NPOLLS_DEFAULT;
	port_threshold = PORT_THRESHOLD_DEFAULT;

	/* This is a trick to have long options only as this is the standard
       for how netstr works. However, if one wanted to unglue this piece
       it wouldn't be too difficult                                      */
	while (1) {
		static struct option long_options[] = {
			{"if", required_argument, 0, 'i'},
			{"threshold", required_argument, 0, 'T'},
			{"polls", required_argument, 0, 'p'},
			{"no-verify", no_argument, 0, 'V'},
			{"extra", no_argument, 0, 'X'},
			{0, 0, 0, 0}
		};

		int option_index = 0;

		c = getopt_long(argc, argv, "", long_options, &option_index);

		if (c == -1)
			break;

		switch (c) {
		case 'i':
			pcap_dev = optarg;
			break;
		case 'T':
			port_threshold = u_int_check(optarg);
			break;
		case 'p':
			npolls = u_int_check(optarg);
			break;
		case 'V':
			verify_port = 0;
			break;
		case 'X':
			xflag = 1;
			break;
		case 'u':
			printf("%s\n", PASSIVE_USAGE);
			return EXIT_SUCCESS;
			break;
		default:
			printf("%s\n", PASSIVE_USAGE);
			return EXIT_FAILURE;
			break;
		}
	}

	isroot_uid(); /* call utils  isroot_uid? */

	/* Strip off any none getopt arguments for pcap filter */
	if (!filter)
		filter = copy_argv(&argv[optind]);

	/* Initialize the interface to listen on */
	if ((!pcap_dev)
	    && ((pcap_dev = pcap_lookupdev(errbuf)) == NULL)) {
		fprintf(stderr, "%s\n", errbuf);
		return EXIT_FAILURE;
	}

	if ((handle = pcap_open_live(pcap_dev, 68, 0, 0, errbuf)) == NULL) {
		fprintf(stderr, "%s\n", errbuf);
		return EXIT_FAILURE;
	}

	pcap_lookupnet(pcap_dev, &net, &mask, errbuf);	/* Get netinfo */

	if (filter) {
		if (pcap_compile(handle, &program, filter, 0, net) == -1) {
			fprintf(stderr, "Error - `IP: pcap_compile() IP'\n");
			return EXIT_FAILURE;
		}

		if (pcap_setfilter(handle, &program) == -1) {
			fprintf(stderr, "Error - `IP: pcap_setfilter()'\n");
			return EXIT_FAILURE;
		}

		pcap_freecode(&program);
	}

	printf("Starting capturing engine on %s...\n", pcap_dev);
	pcap_loop(handle, npolls, passive_pcap4, NULL);
	printf("Closing capturing engine...\n");
	pcap_close(handle);
	print_hosts();

	return EXIT_SUCCESS;
}
Ejemplo n.º 13
0
int main(int argc,char *argv[])
{
	if(argc!=2)
	{
		printf("%s <number>\n",argv[0]);
		return 0;
	}
	pcap_t *handle;
	pcap_if_t *alldev;
	pcap_if_t *p;
	char error[100];

	struct in_addr net_ip_addr;
	struct in_addr net_mask_addr;
	struct ether_header *ethernet;

	char *net_ip_string;
	char *net_mask_string;
	char *interface;
	u_int32_t net_ip;
	u_int32_t net_mask;

	struct pcap_pkthdr pack; 
	const u_char *content;

	int i=0,num;
	if(pcap_findalldevs(&alldev,error)==-1)
	{
		printf("find all devices is error\n");
		return 0;
	}
	for(p=alldev;p;p=p->next)
	{
		printf("%d:%s\n",++i,p->name);
		if(p->description)
		{
			printf("%s\n",p->description);
		}
	}
	if(i==1)
		interface=p->name;
	else
	{
		printf("please input which interface you want to use\n");
		scanf("%d",&num);
		if(num<1||num>i)
		{
			printf("interface is unavillible\n");
			return 0;
		}
		for(p=alldev,i=1;i<=num;p=p->next,i++)
			interface=p->name;
	}
	/*
	if((interface=pcap_lookupdev(error))==NULL)
	{
		printf("%s\n",error);
		return 0;
	}*/
	if((handle=pcap_open_live(interface,max,1,0,error))==NULL)
	{
		printf("%s\n",error);
		return 0;
	}
	if(pcap_lookupnet(interface,&net_ip,&net_mask,error)==-1)
	{
		printf("%s\n",error);
		return 0;
	}
	printf("Interface is:%s\n",interface);
	net_ip_addr.s_addr=net_ip;
	net_ip_string=inet_ntoa(net_ip_addr);
	printf("The ip is:%s\n",net_ip_string);
	net_mask_addr.s_addr=net_mask;
	net_mask_string=inet_ntoa(net_mask_addr);
	printf("The mask is:%s\n",net_mask_string);
	pcap_loop(handle,atoi(argv[1]),call,NULL);
	pcap_freealldevs(alldev);
	return 1;
}
Ejemplo n.º 14
0
void *networkScan(void *arg)
{
	bpf_u_int32 netaddr=0, mask=0;    /* To Store network address and netmask   */ 
	struct bpf_program filter;        /* Place to store the BPF filter program  */ 
	char errbuf[PCAP_ERRBUF_SIZE];    /* Error buffer                           */ 
	pcap_t *descr = NULL;             /* Network interface handler              */
	char *ethernet = DEVICENAME;
	device_info dev_info;				/*my ethernet address*/
	device_info gate_info;
	NodeStatus node_status;			//노드 정보
	network_grub_args *n_args = 0;
	sendkill_grub_args k_args;

	pthread_t t_id1 = 0;
	pthread_t t_id2 = 0;
	int state1 = 0;
	int state2 = 0;
	receiver_grub_args grub;
	int i;

	memset(&node_status, 0, sizeof(NodeStatus));

	n_args = (network_grub_args*)arg;

	memset(errbuf,0,PCAP_ERRBUF_SIZE); 
	/* Open network device for packet capture */ 
	if ((descr = pcap_open_live(ethernet, MAXBYTES2CAPTURE, 0,  512, errbuf))==NULL){
		fprintf(stderr, "1ERROR: %s\n", errbuf);
		exit(1);
	}

	/* Look up info from the capture device. */ 
	if( pcap_lookupnet(ethernet , &netaddr, &mask, errbuf) == -1){
		fprintf(stderr, "2ERROR: %s\n", errbuf);
		exit(1);
	}

	/* Compiles the filter expression into a BPF filter program */ 
	if ( pcap_compile(descr, &filter, "tcp or arp", 1, mask) == -1){
		fprintf(stderr, "3ERROR: %s\n", pcap_geterr(descr) );
		exit(1);
	}

	/* Load the filter program into the packet capture device. */ 
	if (pcap_setfilter(descr,&filter) == -1){
		fprintf(stderr, "4ERROR: %s\n", pcap_geterr(descr) );
		exit(1);
	}

	get_device_info(&dev_info);

	k_args.n_args = n_args;
	k_args.gate_info = &gate_info;
	k_args.descr = descr;

	while(1) {			/* get gateway*/
		const unsigned char *packet = NULL; //packet
		struct pcap_pkthdr *p_pkthdr = 0;

		packet = make_arp_packet(dev_info, n_args->g_ip);

		pcap_sendpacket(descr, packet, 42);
		if (pcap_next_ex(descr, &p_pkthdr, &packet) != 1) {
			continue;
		}
		if(gateway_get(packet, n_args->g_ip, k_args.gate_info))
			break;
	}

	printf("GateWay MAC: ");
	for(i=0; i<6;i++) {
		printf("%02X:", k_args.gate_info->macaddr[i]);
	}

	printf("\nGateWay IP: ");
	for(i=0; i<4;i++) {
		printf("%d.", k_args.gate_info->ipaddr[i]);
	}
	puts("");

	grub.p_descr = descr;
	grub.p_node_status = &node_status;
	memcpy( (char*)&grub+8, (unsigned char*)&dev_info+6, 4);

	state1 = pthread_create(&t_id1, NULL, receiver, &grub);
	// puts("thread start");
	if (state1 != 0) {
		fprintf(stderr, "pthread_create() error\n");
		return 0;
	}

	state2 = pthread_create(&t_id2, NULL, send_kill_packet, &k_args);
	// puts("thread start");
	if (state2 != 0) {
		fprintf(stderr, "pthread_create() error\n");
		return 0;
	}

	// puts("thread start2");
	while(1) {
		traffic_flag = 0;
		memset(&node_status, 0, sizeof(NodeStatus));
		send_arp_packet(descr, dev_info);
		
		sleep(1);
		printf("network node status!!!!\n");
		for(i=1; i<255; i++) {
			if(node_status.node[i].status == 1) {
				printf("%6d", i);
			} else {
				printf("%6d", 0);
			}

			if(i%15 == 0)
				puts("");
		}
		puts("");

		traffic_flag = 1;

		sleep(30);
	}
	printf("main function exit\n");
	return 0;
}
Ejemplo n.º 15
0
int main(int argc, char **argv) {
	int c, index;
	char *interface = NULL;
	char *file = NULL;
	char *expr = NULL;
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *handle = NULL;
	struct bpf_program fp;          /* The compiled filter expression */
	bpf_u_int32 mask;               /* The netmask of our sniffing device */
	bpf_u_int32 net;                /* The IP of our sniffing device */
	bool set = false;

        opterr = 0;
	while (c = getopt(argc, argv, "hi:r:")) {
		switch (c) {
			case 'h' :
				print_usage();
				return 0;
			case 'i' :
				interface = optarg;
				break;
			case 'r' :
				file = optarg;
				break;
			case '?' :
				if (optopt == 'i' || optopt == 'r' || optopt == 's')
					fprintf(stderr, "Option -%c requires an argument.\n", optopt);
				else if (isprint(optopt))
					fprintf(stderr, "Unknown option -%c.\n", optopt);
				else
					fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
				return 1;
			default :
				goto out;
		}
	}
out:
	for (index = optind; index < argc; index++)
		expr = argv[index];

	if (file) {
		interface = NULL;
		handle = pcap_open_offline(file, errbuf);
		if (!handle) {
			fprintf(stderr, "Couldn't open device : %s\n", errbuf);
			return (2);
		}
	} else {
		if (interface) {
//                      printf("User Passed Interface : %s\n", interface);
		} else {
			interface = pcap_lookupdev(errbuf);
			if (!interface) {
				fprintf(stderr, "Couldn't find default device : %s\n", errbuf);
				return (2);
			}
		}
	}
	
	if (interface) {
		handle = pcap_open_live(interface, BUFSIZ, 1, -1, errbuf);
		if (!handle) {
			fprintf(stderr, "Couldn't open device : %s\n", errbuf);
			return (2);
		}
	}

	if (pcap_datalink(handle) != DLT_EN10MB) {
		fprintf(stderr, "Device %s doesn't provide Ethernet headers - not supported\n", interface);
		return (2);
	}

	if (expr) {
		if (interface && (pcap_lookupnet(interface, &net, &mask, errbuf) == -1)) {
			fprintf(stderr, "Can't get netmask for device %s\n", interface);
			net = 0;
			mask = 0;
		} else {
			net = 0;
			mask = 0;
		}
		if (pcap_compile(handle, &fp, expr, 0, net) == -1) {
			fprintf(stderr, "Couldn't parse filter %s: %s\n", expr, pcap_geterr(handle));
			return(2);
		}
		set = true;
		if (pcap_setfilter(handle, &fp) == -1) {
			fprintf(stderr, "Couldn't install filter %s: %s\n", expr, pcap_geterr(handle));
			return(2);
		}
	}

	pcap_loop(handle, 1000, got_packet, NULL);
		
	if (set)
		pcap_freecode(&fp);

	pcap_close(handle);

return 0;
}
Ejemplo n.º 16
0
/*
 * process an input file or device
 * May be repeated.
 * If start is false, do not initiate new connections
 */
static void process_infile(const std::string &expression,const char *device,const std::string &infile)
{
    char error[PCAP_ERRBUF_SIZE];
    pcap_t *pd=0;
    int dlt=0;
    pcap_handler handler;

    if (infile!=""){
        std::string file_path = infile;
        // decompress input if necessary
#ifdef HAVE_INFLATER
        for(std::vector<inflater>::const_iterator it = inflaters.begin(); it != inflaters.end(); it++) {
            if(it->appropriate(infile)) {
                int fd = it->invoke(infile);
                file_path = ssprintf("/dev/fd/%d", fd);
                if(fd < 0) {
                    std::cerr << "decompression of '" << infile << "' failed" << std::endl;
                    exit(1);
                }
                if(access(file_path.c_str(), R_OK)) {
                    std::cerr << "decompression of '" << infile << "' is not available on this system" << std::endl;
                    exit(1);
                }
                break;
            }
        }
#endif
	if ((pd = pcap_open_offline(file_path.c_str(), error)) == NULL){	/* open the capture file */
	    die("%s", error);
	}
	dlt = pcap_datalink(pd);	/* get the handler for this kind of packets */
	handler = find_handler(dlt, infile.c_str());
    } else {
	/* if the user didn't specify a device, try to find a reasonable one */
	if (device == NULL){
	    if ((device = pcap_lookupdev(error)) == NULL){
		die("%s", error);
	    }
	}

	/* make sure we can open the device */
	if ((pd = pcap_open_live(device, SNAPLEN, !opt_no_promisc, 1000, error)) == NULL){
	    die("%s", error);
	}
#if defined(HAVE_SETUID) && defined(HAVE_GETUID)
	/* drop root privileges - we don't need them any more */
	if(setuid(getuid())){
	    perror("setuid");
	}
#endif
	/* get the handler for this kind of packets */
	dlt = pcap_datalink(pd);
	handler = find_handler(dlt, device);
    }

    /* If DLT_NULL is "broken", giving *any* expression to the pcap
     * library when we are using a device of type DLT_NULL causes no
     * packets to be delivered.  In this case, we use no expression, and
     * print a warning message if there is a user-specified expression
     */
#ifdef DLT_NULL_BROKEN
    if (dlt == DLT_NULL && expression != ""){
	DEBUG(1)("warning: DLT_NULL (loopback device) is broken on your system;");
	DEBUG(1)("         filtering does not work.  Recording *all* packets.");
    }
#endif /* DLT_NULL_BROKEN */

    DEBUG(20) ("filter expression: '%s'",expression.c_str());

    /* install the filter expression in libpcap */
    struct bpf_program	fcode;
    if (pcap_compile(pd, &fcode, expression.c_str(), 1, 0) < 0){
	die("%s", pcap_geterr(pd));
    }

    if (pcap_setfilter(pd, &fcode) < 0){
	die("%s", pcap_geterr(pd));
    }

    /* initialize our flow state structures */

    /* set up signal handlers for graceful exit (pcap uses onexit to put
     * interface back into non-promiscuous mode
     */
    portable_signal(SIGTERM, terminate);
    portable_signal(SIGINT, terminate);
#ifdef SIGHUP
    portable_signal(SIGHUP, terminate);
#endif

    /* start listening or reading from the input file */
    if (infile == "") DEBUG(1) ("listening on %s", device);
    if (pcap_loop(pd, -1, handler, (u_char *)tcpdemux::getInstance()) < 0){
	
	die("%s: %s", infile.c_str(),pcap_geterr(pd));
    }
}
Ejemplo n.º 17
0
/**
 * Open a network adapter and set it up for packet input
 *
 * @param adapter_num the index of the adapter to use
 * @param arg argument to pass to input
 * @return an adapter handle on success, NULL on failure
 */
static struct pcapif_private*
pcapif_init_adapter(int adapter_num, void *arg)
{
  int i;
  int number_of_adapters;
  struct pcapif_private *pa;
  char errbuf[PCAP_ERRBUF_SIZE+1];
  
  pcap_if_t *alldevs;
  pcap_if_t *d;
  pcap_if_t *used_adapter = NULL;

  pa = (struct pcapif_private *)malloc(sizeof(struct pcapif_private));
  if (!pa) {
    printf("Unable to alloc the adapter!\n");
    return NULL;
  }

  memset(pa, 0, sizeof(struct pcapif_private));
  pa->input_fn_arg = arg;

  /* Retrieve the interfaces list */
  if (pcap_findalldevs(&alldevs, errbuf) == -1) {
    free(pa);
    return NULL; /* no adapters found */
  }
  /* get number of adatpers and adapter pointer */
  for (d = alldevs, number_of_adapters = 0; d != NULL; d = d->next, number_of_adapters++) {
    if (number_of_adapters == adapter_num) {
      char *desc = d->description;
      size_t len;

      len = strlen(d->name);
      LWIP_ASSERT("len < ADAPTER_NAME_LEN", len < ADAPTER_NAME_LEN);
      strcpy(pa->name, d->name);

      used_adapter = d;
      /* format vendor description */
      if (desc != NULL) {
        len = strlen(desc);
        if (strstr(desc, " ' on local host") != NULL) {
          len -= 16;
        }
        else if (strstr(desc, "' on local host") != NULL) {
          len -= 15;
        }
        if (strstr(desc, "Network adapter '") == desc) {
          len -= 17;
          desc += 17;
        }
        len = LWIP_MIN(len, ADAPTER_DESC_LEN-1);
        strncpy(pa->description, desc, len);
        pa->description[len] = 0;
      } else {
        strcpy(pa->description, "<no_desc>");
      }
    }
  }

#ifndef PCAPIF_LIB_QUIET
  /* Scan the list printing every entry */
  for (d = alldevs, i = 0; d != NULL; d = d->next, i++) {
    char *desc = d->description;
    char descBuf[128];
    size_t len;
    const char* devname = d->name;;
    if (d->name == NULL) {
      devname = "<unnamed>";
    } else {
      if (strstr(devname, "\\Device\\") == devname) {
        /* windows: strip the first part */
        devname += 8;
      }
    }
    printf("%2i: %s\n", i, devname);
    if (desc != NULL) {
      /* format vendor description */
      len = strlen(desc);
      if (strstr(desc, " ' on local host") != NULL) {
        len -= 16;
      }
      else if (strstr(desc, "' on local host") != NULL) {
        len -= 15;
      }
      if (strstr(desc, "Network adapter '") == desc) {
        len -= 17;
        desc += 17;
      }
      len = LWIP_MIN(len, 127);
      strncpy(descBuf, desc, len);
      descBuf[len] = 0;
      printf("     Desc: \"%s\"\n", descBuf);
    }
  }
#endif /* PCAPIF_LIB_QUIET */

  /* invalid adapter index -> check this after printing the adapters */
  if (adapter_num < 0) {
    printf("Invalid adapter_num: %d\n", adapter_num);
    free(pa);
    pcap_freealldevs(alldevs);
    return NULL;
  }
  /* adapter index out of range */
  if (adapter_num >= number_of_adapters) {
    printf("Invalid adapter_num: %d\n", adapter_num);
    free(pa);
    pcap_freealldevs(alldevs);
    return NULL;
  }
#ifndef PCAPIF_LIB_QUIET
  printf("Using adapter_num: %d\n", adapter_num);
#endif /* PCAPIF_LIB_QUIET */
  /* set up the selected adapter */

  LWIP_ASSERT("used_adapter != NULL", used_adapter != NULL);

  /* Open the device */
  pa->adapter = pcap_open_live(used_adapter->name,/* name of the device */
                               65536,             /* portion of the packet to capture */
                                                  /* 65536 guarantees that the whole packet will be captured on all the link layers */
                               PCAP_OPENFLAG_PROMISCUOUS,/* promiscuous mode */
#if PCAPIF_RX_USE_THREAD
                               /*-*/1,                /* don't wait at all for lower latency */
#else
                               1,                /* wait 1 ms in ethernetif_poll */
#endif
                               errbuf);           /* error buffer */
  if (pa->adapter == NULL) {
    printf("\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
    /* Free the device list */
    pcap_freealldevs(alldevs);
    free(pa);
    return NULL;
  }
  printf("Using adapter: \"%s\"\n", pa->description);
  pcap_freealldevs(alldevs);

#if PCAPIF_HANDLE_LINKSTATE
  pa->link_state = pcapifh_linkstate_init(pa->name);
  pa->last_link_event = PCAPIF_LINKEVENT_UNKNOWN;
#endif /* PCAPIF_HANDLE_LINKSTATE */

  return pa;
}
Ejemplo n.º 18
0
/* Convert new nsiod to pcap descriptor. Other parameters have the same meaning
 * as for pcap_open_live in pcap(3).
 *   device   : pcap-style device name
 *   snaplen  : size of packet to be copied to hanler
 *   promisc  : whether to open device in promiscuous mode
 *   bpf_fmt   : berkeley filter
 * return value: NULL if everything was okay, or error string if error occurred. */
char* nsock_pcap_open(nsock_pool nsp, nsock_iod nsiod, const char *pcap_device, int snaplen,
                      int promisc, const char *bpf_fmt, ...) {
  msiod *nsi = (msiod *)nsiod;
  mspool *ms = (mspool *)nsp;
  mspcap *mp = (mspcap *)nsi->pcap;
  static char errorbuf[128];
  char err0r[PCAP_ERRBUF_SIZE];
  /* packet filter string */
  char bpf[4096];
  va_list ap;
  int failed, datalink;
  char *e;

  gettimeofday(&nsock_tod, NULL);

#ifdef PCAP_CAN_DO_SELECT

#if PCAP_BSD_SELECT_HACK
  /* MacOsX reports error if to_ms is too big (like INT_MAX) with error
   *  FAILED. Reported error: BIOCSRTIMEOUT: Invalid argument
   *  INT_MAX/6 (=357913941) seems to be working... */
  int to_ms = 357913941;
#else
  int to_ms = 200;
#endif /* PCAP_BSD_SELECT_HACK */

#else
  int to_ms = 1;
#endif

  if (mp)
    return "nsock-pcap: this nsi already has pcap device opened";

  mp = (mspcap *)safe_zalloc(sizeof(mspcap));
  nsi->pcap = (void *)mp;

  va_start(ap, bpf_fmt);
  if (Vsnprintf(bpf, sizeof(bpf), bpf_fmt, ap) >= (int)sizeof(bpf)) {
    va_end(ap);
    return "nsock-pcap: nsock_pcap_open called with too-large bpf filter arg";
  }
  va_end(ap);

  if (ms->tracelevel > 0)
      nsock_trace(ms,
                  "PCAP requested on device '%s' with berkeley filter '%s' (promisc=%i snaplen=%i to_ms=%i) (IOD #%li)",
                  pcap_device,bpf, promisc, snaplen, to_ms, nsi->id);

  failed = 0;
  do {
    mp->pt = pcap_open_live((char* )pcap_device, snaplen, promisc, to_ms, err0r);
    if (mp->pt)  /* okay, opened!*/
      break;

    /* sorry, something failed*/
    if (++failed >= 3) {
      mp->pcap_device = strdup(pcap_device);
      fprintf(stderr,
              "Call to pcap_open_live(%s, %d, %d, %d) failed three times. Reported error: %s\n"
              "There are several possible reasons for this, depending on your operating system:\n"
              "LINUX: If you are getting Socket type not supported, try modprobe af_packet or recompile your kernel with PACKET enabled.\n"
              "*BSD:  If you are getting device not configured, you need to recompile your kernel with Berkeley Packet Filter support.  If you are getting No such file or directory, try creating the device (eg cd /dev; MAKEDEV <device>; or use mknod).\n"
              "*WINDOWS:  Nmap only supports ethernet interfaces on Windows for most operations because Microsoft disabled raw sockets as of Windows XP SP2.  Depending on the reason for this error, it is possible that the --unprivileged command-line argument will help.\n"
              "SOLARIS:  If you are trying to scan localhost and getting '/dev/lo0: No such file or directory', complain to Sun.  I don't think Solaris can support advanced localhost scans.  You can probably use \"-PN -sT localhost\" though.\n\n",
        pcap_device, snaplen, promisc, to_ms, err0r);
      return "nsock-pcap: can't open pcap! Are you root?";
    }

    fprintf(stderr,
            "pcap_open_live(%s, %d, %d, %d) FAILED. Reported error: %s. Will wait %d seconds then retry.\n",
            pcap_device, snaplen, promisc, to_ms, err0r, 4*failed);
    sleep(4* failed);
  } while (1);

  e = nsock_pcap_set_filter(mp->pt, pcap_device, bpf);
  if (e)
    return e;

#ifdef WIN32
  /* We want any responses back ASAP */
  pcap_setmintocopy(mp->pt, 1);
#endif

  mp->l3_offset = nsock_pcap_get_l3_offset(mp->pt, &datalink);
  mp->snaplen = snaplen;
  mp->datalink = datalink;
  mp->pcap_device = strdup(pcap_device);
#ifdef PCAP_CAN_DO_SELECT
  mp->pcap_desc = pcap_get_selectable_fd(mp->pt);
#else
  mp->pcap_desc = -1;
#endif
  mp->readsd_count = 0;

  /* Without setting this ioctl, some systems (BSDs, though it depends on the
   * release) will buffer packets in non-blocking mode and only return them in a
   * bunch when the buffer is full. Setting the ioctl makes each one be
   * delivered immediately. This is how Linux works by default. See the comments
   * surrounding the setting of BIOCIMMEDIATE in libpcap/pcap-bpf.c. */
#ifdef BIOCIMMEDIATE
  if (mp->pcap_desc != -1) {
    int immediate = 1;

    if (ioctl(mp->pcap_desc, BIOCIMMEDIATE, &immediate) < 0)
      fatal("Cannot set BIOCIMMEDIATE on pcap descriptor");
  }
#endif

  /* Set device non-blocking */
  if (pcap_setnonblock(mp->pt, 1, err0r) < 0) {
    /* I can't do select() on pcap! blocking + no_select is fatal */
    if(mp->pcap_desc < 0){
      Snprintf(errorbuf, sizeof(errorbuf),
               "nsock-pcap: Failed to set pcap descriptor on device %s to nonblocking state: %s",
               pcap_device, err0r);
      return errorbuf;
    }

    /* When we use bsd hack we also need to set non-blocking */
#ifdef PCAP_BSD_SELECT_HACK
    Snprintf(errorbuf, sizeof(errorbuf),
             "nsock-pcap: Failed to set pcap descriptor on device %s to nonblocking state: %s",
             pcap_device, err0r);
    return errorbuf;
#endif

    /* in other case, we can accept blocking pcap */
    fprintf(stderr, "Failed to set pcap descriptor on device %s to nonblocking state: %s",
            pcap_device, err0r);
  }

  if (ms->tracelevel > 0)
      nsock_trace(ms, "PCAP created successfully on device '%s' (pcap_desc=%i bsd_hack=%i to_valid=%i l3_offset=%i) (IOD #%li)",
      pcap_device,
      mp->pcap_desc,
#if PCAP_BSD_SELECT_HACK
      1,
#else
      0,
#endif
#if PCAP_RECV_TIMEVAL_VALID
      1,
#else
      0,
#endif
      mp->l3_offset,
      nsi->id);

  return NULL;
}
Ejemplo n.º 19
0
int main()

{
    char *dev, errbuf[PCAP_ERRBUF_SIZE]; /* The device to sniff on, Error string */

    /* Define the device */
    dev = pcap_lookupdev(errbuf); //find the dev
    if (dev == NULL) {
        fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
        return(2);
    }
    printf("Device: %s\n", dev);

    pcap_t *handle; /* Session handle */

    /* Open the session in promiscuous mode */
      handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); // dev session open
      if (handle == NULL) {
          fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
          return(2);
      }

      char send_buf[sizeof(libnet_ethernet_hdr) + sizeof(libnet_arp_hdr)] =  {0,}; // send_buf[0], send_buf[1], send_buf[2]
      libnet_ethernet_hdr* eth_hdr = (libnet_ethernet_hdr*)send_buf;
      // eth_hdr setting place
      // victim MAC address setting
      // if i want to arp snooping to everyone of netwrok you can write FF-FF-FF-FF-FF-FF
      send_buf[0] = 0xD0;
      send_buf[1] = 0x50;
      send_buf[2] = 0x99;
      send_buf[3] = 0xA4;
      send_buf[4] = 0x04;
      send_buf[5] = 0x4D;

      // attcker Mac address setting
      send_buf[6] = 0x00;
      send_buf[7] = 0x0c;
      send_buf[8] = 0x29;
      send_buf[9] = 0xe1;
      send_buf[10] = 0xaa;
      send_buf[11] = 0x9a;

      //arp type setting
      eth_hdr -> ether_type = ETHERTYPE_ARP;

      printf("                  ** eth0 **\n");
      printf("      Attcker MAC    ->    Victim MAC \n");
      printf("   %02X:%02X:%02X:%02X:%02X:%02X -> %02X:%02X:%02X:%02X:%02X:%02X\n\n\n",
                  eth_hdr->ether_shost[0],
                  eth_hdr->ether_shost[1],
                  eth_hdr->ether_shost[2],
                  eth_hdr->ether_shost[3],
                  eth_hdr->ether_shost[4],
                  eth_hdr->ether_shost[5],
                  eth_hdr->ether_dhost[0],
                  eth_hdr->ether_dhost[1],
                  eth_hdr->ether_dhost[2],
                  eth_hdr->ether_dhost[3],
                  eth_hdr->ether_dhost[4],
                  eth_hdr->ether_dhost[5]);


      if(eth_hdr -> ether_type == ETHERTYPE_ARP)
      {
          libnet_arp_hdr* arp_hdr = (libnet_arp_hdr*)(send_buf + sizeof(libnet_ethernet_hdr));

          arp_hdr -> ar_hrd = ARPHRD_ETHER;
          arp_hdr -> ar_pro = ETHERTYPE_IP;
          arp_hdr -> ar_hln = 0x06;
          arp_hdr -> ar_pln = 0x04;
          if(arp_hdr -> ar_op == ARPOP_REQUEST || arp_hdr -> ar_op == ARPOP_REPLY)
          {
          printf("   %02X:%02X:%02X:%02X:%02X:%02X -> %02X:%02X:%02X:%02X:%02X:%02X\n\n\n",
                      arp_hdr->attack_HA[0] = 0x08,
                      arp_hdr->attack_HA[1] = 0x08,
                      arp_hdr->attack_HA[2],
                      arp_hdr->attack_HA[3],
                      arp_hdr->attack_HA[4],
                      arp_hdr->attack_HA[5],
                      arp_hdr->victim_HA[0],
                      arp_hdr->victim_HA[1],
                      arp_hdr->victim_HA[2],
                      arp_hdr->victim_HA[3],
                      arp_hdr->victim_HA[4],
                      arp_hdr->victim_HA[5]);
              }
      }





      // ar_hdr setting

      //vmware: ip = 10.100.111.105 // MAC = 00:0c:29:e1:aa:9a
      //window: ip = 10.100.111. 98 // MAC = D0-50-99-A4-04-4D


      pcap_close(handle);

   return(0);

}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
	struct bpf_program fcode;
	pcap_handler printer;
	char ebuf[PCAP_ERRBUF_SIZE];
	int c,i,snaplen=512,size,packetcnt;
	bpf_u_int32 myself, localnet, netmask;
	unsigned char *pcap_userdata;

	filter_rule = argv[1];
	signal(SIGINT,sig_int);

	opterr =0;
	if(argc-1 <1)
	{
		usage();
		exit(1);
	}

	while( (c=getopt(argc,argv,"i:c:pher")) != -1) {
		switch(c) {
			case 'i' :
				device = optarg;
				break;
			case 'p' :
				pflag = 1;
				break;
			case 'c':
				cflag = 1;
				packetcnt = atoi(optarg);
				if(packetcnt <=0) {
					fprintf(stderr, "invalid pacet number %s",optarg);
					exit(1);
				}
				break;
			case 'e':
				eflag =1;
				break;
			case 'r':
				rflag =1;
				break;
			case 'h':
				usage();
				exit(1);
		}
	}

	if(device == NULL) {
		if( (device = pcap_lookupdev(ebuf) ) ==NULL)
		{
			perror(ebuf);
			exit(-1);
		}
	}
	fprintf(stdout,"device = %s\n", device);

	pd = pcap_open_live(device , snaplen, PROMISCOUS, 1000, ebuf);
	if(pd == NULL) {
		perror(ebuf);
		exit(-1);
	}

	i = pcap_snapshot(pd);
	if(snaplen <i) {
		perror(ebuf);
		exit(-1);
		}
	if(pcap_lookupnet(device, &localnet, &netmask, ebuf) <0) {
		perror(ebuf);
		exit(-1);
	}

	setuid(getuid());

	if(pcap_compile(pd, &fcode, filter_rule , 0, netmask)<0) {
		perror(ebuf);
		exit(-1);
	}

	if(pcap_setfilter(pd, &fcode) <0) {
		perror(ebuf);
		exit(-1);
	}

	fflush(stderr);

	printer = lookup_printer(pcap_datalink(pd));
	pcap_userdata = 0;
	if(pcap_loop(pd,packetcnt, printer, pcap_userdata) <0) {
		perror("pcap_loop error");
		exit(-1);
	}
	
	pcap_close(pd);
	exit(0);
}
Ejemplo n.º 21
0
int main(int argc, char **argv) {

    int i; 
    char *dev;  
    char errbuf[PCAP_ERRBUF_SIZE]; 

    pcap_t* descr; 
    const u_char *packet; 
    struct pcap_pkthdr hdr;     /* pcap.h */ 
    struct ether_header *eptr;  /* net/ethernet.h */ 
    u_char *ptr; /* printing out hardware header info */ 
    /* grab a device to peak into... */ 
    dev = pcap_lookupdev(errbuf); 

    if(dev == NULL) { 
        printf("%s\n",errbuf); 
        exit(1); 
    } 

    printf("DEV: %s\n",dev); 
    descr = pcap_open_live(dev,BUFSIZ,0,-1,errbuf); 

    if(descr == NULL) { 
        printf("pcap_open_live(): %s\n",errbuf); 
        exit(1); 
    } 

    packet = pcap_next(descr,&hdr); 

    if(packet == NULL) {/* dinna work *sob* */ 
        printf("Didn't grab packet\n"); 
        exit(1); 
    } 

    printf("Grabbed packet of length %d\n",hdr.len); 
    printf("Recieved at ..... %s\n",ctime((const time_t*)&hdr.ts.tv_sec));  
    printf("Ethernet address length is %d\n",ETHER_HDR_LEN); 
    /* lets start with the ether header... */ 
    eptr = (struct ether_header *) packet; 
    /* Do a couple of checks to see what packet type we have..*/ 
    if (ntohs (eptr->ether_type) == ETHERTYPE_IP)  { 
        printf("Ethernet type hex:%x dec:%d is an IP packet\n", 
                ntohs(eptr->ether_type), 
                ntohs(eptr->ether_type)); 
    }else  if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) { 
        printf("Ethernet type hex:%x dec:%d is an ARP packet\n", 
                ntohs(eptr->ether_type), 
                ntohs(eptr->ether_type)); 
    }else { 
        printf("Ethernet type %x not IP", ntohs(eptr->ether_type)); 
        exit(1); 
    } 
    /* THANK YOU RICHARD STEVENS!!! RIP*/ 
    ptr = eptr->ether_dhost; 
    i = ETHER_ADDR_LEN; 
    printf(" Destination Address:  "); 
    do{ 
        printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++); 
    }while(--i>0); 
    printf("\n"); 
    ptr = eptr->ether_shost; 
    i = ETHER_ADDR_LEN; 
    printf(" Source Address:  "); 
    do{ 
        printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++); 
    }while(--i>0); 
    printf("\n"); 
    return 0; 
} 
Ejemplo n.º 22
0
Archivo: p0f.c Proyecto: kernevil/p0f
static void prepare_pcap(void) {

  char pcap_err[PCAP_ERRBUF_SIZE];
  u8* orig_iface = use_iface;

  if (read_file) {

    if (set_promisc)
      FATAL("Dude, how am I supposed to make a file promiscuous?");

    if (use_iface)
      FATAL("Options -i and -r are mutually exclusive.");

    if (access((char*)read_file, R_OK))
      PFATAL("Can't access file '%s'.", read_file);

    pt = pcap_open_offline((char*)read_file, pcap_err);

    if (!pt) FATAL("pcap_open_offline: %s", pcap_err);

    SAYF("[+] Will read pcap data from file '%s'.\n", read_file);

  } else {

    if (!use_iface) {

      /* See the earlier note on libpcap SEGV - same problem here.
         Also, this retusns something stupid on Windows, but hey... */
     
      if (!access("/sys/class/net", R_OK | X_OK) || errno == ENOENT)
        use_iface = (u8*)pcap_lookupdev(pcap_err);

      if (!use_iface)
        FATAL("libpcap is out of ideas; use -i to specify interface.");

    }

#ifdef __CYGWIN__

    /* On Windows, interface names are unwieldy, and people prefer to use
       numerical IDs. */

    else {

      int iface_id;

      if (sscanf((char*)use_iface, "%u", &iface_id) == 1) {
        use_iface = find_interface(iface_id);
      }
  
    }

    pt = pcap_open_live((char*)use_iface, SNAPLEN, set_promisc, 250, pcap_err);

#else 

    /* PCAP timeouts tend to be broken, so we'll use a minimum value
       and rely on select() instead. */

    pt = pcap_open_live((char*)use_iface, SNAPLEN, set_promisc, 1, pcap_err);

#endif /* ^__CYGWIN__ */

    if (!orig_iface)
      SAYF("[+] Intercepting traffic on default interface '%s'.\n", use_iface);
    else
      SAYF("[+] Intercepting traffic on interface '%s'.\n", use_iface);

    if (!pt) FATAL("pcap_open_live: %s", pcap_err);

  }

  link_type = pcap_datalink(pt);

}
Ejemplo n.º 23
0
int main(void)
{
        char *device = "eth0";
        char errbuf[PCAP_ERRBUF_SIZE];
        pcap_t *phandle;
        bpf_u_int32 ipaddress, ipmask;
        struct bpf_program fcode;
        int datalink;
        if ((device = pcap_lookupdev(errbuf)) == NULL)
		{
			perror(errbuf);
			return 0;
		}
        else
		{
			printf("device: %s\n", device);
		}

        phandle = pcap_open_live(device, 200, 0, 500, errbuf);
        if (phandle == NULL)
        {
			perror(errbuf);
			return 0;
		}

        if (pcap_lookupnet(device, &ipaddress, &ipmask, errbuf) == -1)
		{
			perror(errbuf);
			return 0;
		}
        else 
		{                                         
            char net[INET_ADDRSTRLEN], mask[INET_ADDRSTRLEN];
            if (inet_ntop(AF_INET, &ipaddress, net, sizeof(net)) == NULL)
			{
				perror("inet_ntop");
			}
            else if (inet_ntop(AF_INET, &ipmask, mask, sizeof(net)) == NULL)
            {
				perror("inet_ntop");
			}
            printf("IP Address: %s, Network Mask: %s\n", net, mask);
        }

		int bflag = 1;
		while(bflag)
		{
			printf("Input Packet Filter:>");
			char filterString[1024];
			scanf("%s",filterString);
			if (pcap_compile(phandle, &fcode, filterString, 0, ipmask) == -1) {
                fprintf(stderr, "pcap_compile: %s,please input again......\n", pcap_geterr(phandle));                
			}
			else
				bflag = 0;
		}

        if (pcap_setfilter(phandle, &fcode) == -1) 
		{
                fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(phandle));
				return 0;
        }

        if ((datalink = pcap_datalink(phandle)) == -1)
		{
                fprintf(stderr, "pcap_datalink: %s\n", pcap_geterr(phandle));
                return 0;
        }
        printf("datalink = %d\n", datalink);
       // capture_packet(datalink, phandle, fcode);
		npacketnum = 0;
		pcap_loop(phandle, 0, pcap_handle, NULL);// 
        return 1;
}
Ejemplo n.º 24
0
/* main function */
int main()
{
	char *dev;
	char erbuf[PCAP_ERRBUF_SIZE];
	struct timeval tim;
	struct pcap_pkthdr hdr;
	char *point;
	char str1[50];
	int i=0,j=0,counter=0;
	char ptr[200];
	pcap_t *descr1;
	/* For setting signal handler */	
	struct sigaction myAction;       
	struct itimerval timer;
	eth=(struct ethhdr *)malloc(sizeof(struct ethhdr));
	len=sizeof(struct ethhdr);
	strcpy(str1,"\0");
	packet=(char*)malloc(1514);
	point=(char *)malloc(100);

	dev=pcap_lookupdev(erbuf);
	if(dev==NULL)
	{
		printf("\n\t\terrbuf : %s\n\n",erbuf);
		exit(1);
	}
	
	descr=pcap_open_live(dev,BUFSIZ,0,-1,erbuf);
	if(descr==NULL)
	{
		printf("\n\t\tCannot open:%s\n",erbuf);
		exit(1);
	}

	do
	{
		printf("\n\t\tWaiting for INIT packet from client : %d \n",counter+1);
		i=pcap_loop(descr,1,my_callback,NULL);// wait for INIT packet
		ether_head();
        	strcpy(str1,"\0");
		strcpy(str1,"SYN 1.");
		memcpy(packet+14,str1,sizeof(str1));

		printf("\n\t\tSending SYNC packet to client : %d\n",counter+1);
		counter++;
		/* Send sync packet containing T1 */		
		i=pcap_sendpacket(descr,packet,1514);  
		if(i==-1)
		{	
			pcap_perror(descr,ptr);
			printf("\n\t\tERROR : %s\n",ptr);
			printf("\n\t\tError in inject function!!!\n");
		}
		
		memset(&myAction,0,sizeof(struct sigaction));
		myAction.sa_handler = CatchAlarm;

		/* block everything in handler */
    		if (sigfillset(&myAction.sa_mask) < 0) 
        		printf("sigfillset() failed");
    		myAction.sa_flags = 0;

    		if (sigaction(SIGALRM, &myAction, 0) < 0)
        		printf("sigaction() failed for SIGALRM");

		alarm(TIMEOUT_SECS);
		pcap_setdirection(descr,PCAP_D_IN);

		/* Wait for packet containig loop for T3 */
		i=pcap_loop(descr,1,my_callback,NULL); 
		if(i==-1)
			printf("\n\n\t\tError in pcap_loop\n");
		else if(i==-2)
		{
			strcpy(str1,"\0");
			strcpy(str1,"ERROR ");       //new
			descr1=pcap_open_live(dev,BUFSIZ,0,-1,erbuf);		
			if(descr1==NULL)
			{
				printf("\n\t\tCannot open:%s\n",erbuf);
				exit(1);
			}
			memcpy(packet+14,str1,sizeof(str1));
			i=pcap_sendpacket(descr1,packet,1514);  /* Sending error packet */
			if(i==-1)
				pcap_perror(descr1,point);
			printf("\n\t\tT3 not received... exiting\n");
			continue;
			pcap_close(descr1);
			
				
		}
		else
		{
			alarm(0);
			printf("\n\t\tDelay request packet received in time\n");
		}

		ether_head();	
	
		//T4 time sent
		strcpy(str1,"\0");
		strcpy(str1,"SYN 3.");
		memcpy(packet+14,str1,sizeof(str1));
		sprintf(str1,"%ld.%ld",t.tv_sec,t.tv_nsec);
		memcpy(packet+20,str1,sizeof(str1));

		i=pcap_sendpacket(descr,packet,1514);  //sending T4
		if(i==-1)
			printf("\n\n\t\tError in sending Delay response packet\n");

		/* Set signal handler for alarm signal */
    		myAction.sa_handler = CatchAlarm;
    		if (sigfillset(&myAction.sa_mask) < 0) /* block everything in handler */
        		printf("sigfillset() failed");
    		myAction.sa_flags = 0;

    		if (sigaction(SIGALRM, &myAction, 0) < 0)
        		printf("sigaction() failed for SIGALRM");
	
	
		alarm(TIMEOUT_SECS);
		pcap_setdirection(descr,PCAP_D_IN);
  		i=pcap_loop(descr,1,my_callback,NULL);   //T4 reply
	
	
		if(i==-1)
				printf("\n\t\tError in pcap_loop()\n");
		else if(i==-2)
		{
			
			strcpy(str1,"\0");
			strcpy(str1,"ERROR ");          //new
			memcpy(packet+14,str1,sizeof(str1));
		
			i=pcap_sendpacket(descr,packet,1514);  //sending error
			printf("\n\t\tT4 reply not received... exiting\n\n");
			continue;

			
		} 
		else
		{
			alarm(0);
			printf("\n\t\tT4 reply received in time\n");
			printf("\n\t\tClient %d : Request satisfied!!!\n\n\n\n\n",counter);
         	}

	}while(1);

         return 0;
}
Ejemplo n.º 25
0
static int l2_packet_init_libpcap(struct l2_packet_data *l2,
				  unsigned short protocol)
{
	bpf_u_int32 pcap_maskp, pcap_netp;
	char pcap_filter[200], pcap_err[PCAP_ERRBUF_SIZE];
	struct bpf_program pcap_fp;

#ifdef CONFIG_WINPCAP
	char ifname[128];
	os_snprintf(ifname, sizeof(ifname), "\\Device\\NPF_%s", l2->ifname);
	pcap_lookupnet(ifname, &pcap_netp, &pcap_maskp, pcap_err);
	l2->pcap = pcap_open_live(ifname, 2500, 0, 10, pcap_err);
	if (l2->pcap == NULL) {
		fprintf(stderr, "pcap_open_live: %s\n", pcap_err);
		fprintf(stderr, "ifname='%s'\n", ifname);
		return -1;
	}
	if (pcap_setnonblock(l2->pcap, 1, pcap_err) < 0)
		fprintf(stderr, "pcap_setnonblock: %s\n",
			pcap_geterr(l2->pcap));
#else /* CONFIG_WINPCAP */
	pcap_lookupnet(l2->ifname, &pcap_netp, &pcap_maskp, pcap_err);
	l2->pcap = pcap_open_live(l2->ifname, 2500, 0, 10, pcap_err);
	if (l2->pcap == NULL) {
		fprintf(stderr, "pcap_open_live: %s\n", pcap_err);
		fprintf(stderr, "ifname='%s'\n", l2->ifname);
		return -1;
	}
	if (pcap_datalink(l2->pcap) != DLT_EN10MB &&
	    pcap_set_datalink(l2->pcap, DLT_EN10MB) < 0) {
		fprintf(stderr, "pcap_set_datalinke(DLT_EN10MB): %s\n",
			pcap_geterr(l2->pcap));
		return -1;
	}
#endif /* CONFIG_WINPCAP */
	os_snprintf(pcap_filter, sizeof(pcap_filter),
		    "not ether src " MACSTR " and "
		    "( ether dst " MACSTR " or ether dst " MACSTR " ) and "
		    "ether proto 0x%x",
		    MAC2STR(l2->own_addr), /* do not receive own packets */
		    MAC2STR(l2->own_addr), MAC2STR(pae_group_addr),
		    protocol);
	if (pcap_compile(l2->pcap, &pcap_fp, pcap_filter, 1, pcap_netp) < 0) {
		fprintf(stderr, "pcap_compile: %s\n", pcap_geterr(l2->pcap));
		return -1;
	}

	if (pcap_setfilter(l2->pcap, &pcap_fp) < 0) {
		fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(l2->pcap));
		return -1;
	}

	pcap_freecode(&pcap_fp);
#ifdef BIOCIMMEDIATE
	/*
	 * When libpcap uses BPF we must enable "immediate mode" to
	 * receive frames right away; otherwise the system may
	 * buffer them for us.
	 */
	{
		unsigned int on = 1;
		if (ioctl(pcap_fileno(l2->pcap), BIOCIMMEDIATE, &on) < 0) {
			fprintf(stderr, "%s: cannot enable immediate mode on "
				"interface %s: %s\n",
				__func__, l2->ifname, strerror(errno));
			/* XXX should we fail? */
		}
	}
#endif /* BIOCIMMEDIATE */

#ifdef CONFIG_WINPCAP
	eloop_register_timeout(0, 100000, l2_packet_receive_timeout,
			       l2, l2->pcap);
#else /* CONFIG_WINPCAP */
	eloop_register_read_sock(pcap_get_selectable_fd(l2->pcap),
				 l2_packet_receive, l2, l2->pcap);
#endif /* CONFIG_WINPCAP */

	return 0;
}
Ejemplo n.º 26
0
int main()
{
   pcap_t *handle;			/* Session handle */
   char *dev;			/* The device to sniff on */
   char errbuf[PCAP_ERRBUF_SIZE];	/* Error string */
   struct bpf_program fp;		/* The compiled filter */
   char filter_exp[]="";	/* The filter expression */
   bpf_u_int32 mask;		/* Our netmask */
   bpf_u_int32 net;		/* Our IP */

   /* Define the device */
   dev = pcap_lookupdev(errbuf);
   if (dev == NULL) {
       fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
       return(2);
   }
   /* Find the properties for the device */
   if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
       fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
       net = 0;
       mask = 0;
   }
   /* Open the session in promiscuous mode */
   handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
   if (handle == NULL) {
       fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
       return(2);
   }
   /* Compile and apply the filter */
   if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
       fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
       return(2);
   }
   if (pcap_setfilter(handle, &fp) == -1) {
       fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
       return(2);
   }
   /* Grab a packet */
   while(1)
   {
       struct pcap_pkthdr *header;
       const u_char *packet;


       const int res = pcap_next_ex(handle, &header, &packet);

       if(res<0)
       {
             break;
       }
       if(res==0)
       {
             continue;
       }

       struct ethhdr * eth = (struct ethhdr*) packet;


       short type = ntohs(eth->h_proto);
       if(type == ETHERTYPE_IP)
       {
           struct iphdr * iph = (struct iphdr *)(packet+ sizeof(struct ethhdr));
           unsigned short iphdrlen;

           iphdrlen = iph->ihl*4;


           memset(&source, 0, sizeof(source));
            source.sin_addr.s_addr = iph->saddr;

            memset(&dest, 0, sizeof(dest));
            dest.sin_addr.s_addr = iph->daddr;



           if(iph->protocol==IPPROTO_TCP)
           {
             printf("--------------------------------------------\n");
             printf("Ethernet Header\n");
             printf("Dest Mac addr : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_dest[0] , eth->h_dest[1] , eth->h_dest[2] , eth->h_dest[3] , eth->h_dest[4] , eth->h_dest[5] );
             printf("Src Mac addr : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_source[0] , eth->h_source[1] , eth->h_source[2] , eth->h_source[3] , eth->h_source[4] , eth->h_source[5] );
             printf("\n");
             printf("IP Header\n");
             printf("Src ip : %s\n",inet_ntoa(source.sin_addr) );
             printf("Dest ip : %s\n",inet_ntoa(dest.sin_addr) );
             printf("\n");


             struct tcphdr * tph = (struct tcphdr *)(packet+ iphdrlen+ sizeof(struct iphdr));

             printf("TCP Header\n");
             printf("Src port : %d\n", ntohs(tph->source));
             printf("Dest port : %d\n", ntohs(tph->dest));


             printf("--------------------------------------------\n");
             printf("\n");
           }


       }

   /* And close the session */
   }
   pcap_close(handle);
   return(0);
}
Ejemplo n.º 27
0
static int
add_or_find_if(pcap_if_t **curdev_ret, pcap_if_t **alldevs, char *name,
    u_int flags, const char *description, char *errbuf)
{
	pcap_t *p;
	pcap_if_t *curdev, *prevdev, *nextdev;
	int this_instance;

	/*
	 * Can we open this interface for live capture?
	 */
	p = pcap_open_live(name, 68, 0, 0, errbuf);
	if (p == NULL) {
		/*
		 * No.  Don't bother including it.
		 * Don't treat this as an error, though.
		 */
		*curdev_ret = NULL;
		return (0);
	}
	pcap_close(p);

	/*
	 * Is there already an entry in the list for this interface?
	 */
	for (curdev = *alldevs; curdev != NULL; curdev = curdev->next) {
		if (strcmp(name, curdev->name) == 0)
			break;	/* yes, we found it */
	}
	if (curdev == NULL) {
		/*
		 * No, we didn't find it.
		 * Allocate a new entry.
		 */
		curdev = malloc(sizeof(pcap_if_t));
		if (curdev == NULL) {
			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "malloc: %s", pcap_strerror(errno));
			return (-1);
		}
		
		/*
		 * Fill in the entry.
		 */
		curdev->next = NULL;
		curdev->name = malloc(strlen(name) + 1);
		strcpy(curdev->name, name);
		if (description != NULL) {
			/*
			 * We have a description for this interface.
			 */
			curdev->description = malloc(strlen(description) + 1);
			strcpy(curdev->description, description);
		} else {
			/*
			 * We don't.
			 */
			curdev->description = NULL;
		}
		curdev->addresses = NULL;	/* list starts out as empty */
		curdev->flags = 0;
		if (ISLOOPBACK(name, flags))
			curdev->flags |= PCAP_IF_LOOPBACK;

		/*
		 * Add it to the list, in the appropriate location.
		 * First, get the instance number of this interface.
		 */
		this_instance = get_instance(name);

		/*
		 * Now look for the last interface with an instance number
		 * less than or equal to the new interface's instance
		 * number - except that non-loopback interfaces are
		 * arbitrarily treated as having interface numbers less
		 * than those of loopback interfaces, so the loopback
		 * interfaces are put at the end of the list.
		 *
		 * We start with "prevdev" being NULL, meaning we're before
		 * the first element in the list.
		 */
		prevdev = NULL;
		for (;;) {
			/*
			 * Get the interface after this one.
			 */
			if (prevdev == NULL) {
				/*
				 * The next element is the first element.
				 */
				nextdev = *alldevs;
			} else
				nextdev = prevdev->next;

			/*
			 * Are we at the end of the list?
			 */
			if (nextdev == NULL) {
				/*
				 * Yes - we have to put the new entry
				 * after "prevdev".
				 */
				break;
			}

			/*
			 * Is the new interface a non-loopback interface
			 * and the next interface a loopback interface?
			 */
			if (!(curdev->flags & PCAP_IF_LOOPBACK) &&
			    (nextdev->flags & PCAP_IF_LOOPBACK)) {
				/*
				 * Yes, we should put the new entry
				 * before "nextdev", i.e. after "prevdev".
				 */
				break;
			}

			/*
			 * Is the new interface's instance number less
			 * than the next interface's instance number,
			 * and is it the case that the new interface is a
			 * non-loopback interface or the next interface is
			 * a loopback interface?
			 *
			 * (The goal of both loopback tests is to make
			 * sure that we never put a loopback interface
			 * before any non-loopback interface and that we
			 * always put a non-loopback interface before all
			 * loopback interfaces.)
			 */
			if (this_instance < get_instance(nextdev->name) &&
			    (!(curdev->flags & PCAP_IF_LOOPBACK) ||
			       (nextdev->flags & PCAP_IF_LOOPBACK))) {
				/*
				 * Yes - we should put the new entry
				 * before "nextdev", i.e. after "prevdev".
				 */
				break;
			}

			prevdev = nextdev;
		}

		/*
		 * Insert before "nextdev".
		 */
		curdev->next = nextdev;

		/*
		 * Insert after "prevdev" - unless "prevdev" is null,
		 * in which case this is the first interface.
		 */
		if (prevdev == NULL) {
			/*
			 * This is the first interface.  Pass back a
			 * pointer to it, and put "curdev" before
			 * "nextdev".
			 */
			*alldevs = curdev;
		} else
			prevdev->next = curdev;
	}
	
	*curdev_ret = curdev;
	return (0);
}
Ejemplo n.º 28
0
int main()
{
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i=0;
	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	u_int netmask;
	char packet_filter[20];
	struct bpf_program fcode;
	
	// 获取网卡列表
	if(pcap_findalldevs(&alldevs, errbuf) == -1)
	{
		fprintf(stderr,"pcap_findalldevs发生错误: %s\n", errbuf);
		exit(1);
	}	
	// 输出网卡信息
	for(i=0,d=alldevs; d; d=d->next,i++)
	{
		ifprint(d,i+1);
		
	}
	if(i==0)
	{
		printf("\n没有找到任何网卡,请确认Winpcap已经安装.\n");
		return -1;
	}
	
	printf("\n\n请输入网卡编号 (1-%d):",i);
	scanf("%d", &inum);
	
	// 检测用户是否指定了有效网卡
	if(inum < 1 || inum > i)
	{
		printf("\n网卡编号超出范围.\n");
		
		// 释放设备列表
		pcap_freealldevs(alldevs);
		return -1;
	}
	
	// 跳转到选择的网卡
	for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
	
	// 打开网卡设备
	if ((adhandle= pcap_open_live(d->name,	// 设备名称
							 65536,			// 捕获全部的数据包 
							 1,				// 设置网卡为混杂模式
							 1000,			// 读超时为1秒
							 errbuf			// 错误缓存
							 )) == NULL)
	{
		fprintf(stderr,"\n不能打开网卡. %s 不被Winpcap支持\n");
		// 释放设备列表
		pcap_freealldevs(alldevs);
		return -1;
	}
	
	// 检测链接层,只支持以太网模式
	if(pcap_datalink(adhandle) != DLT_EN10MB)
	{
		fprintf(stderr,"\n此程序只能运行在以太网上.\n");
		// 释放设备列表
		pcap_freealldevs(alldevs);
		return -1;
	}
	
	if(d->addresses != NULL)
	{   // 返回接口的第一个地址的掩码
		netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
	}
	else
	{   // 如果没有掩码,则默认设置为C类
		netmask=0xffffff; 
	}
	
	// 选择过滤包类型
	int protocol_type; // 0->ip 1->tcp 2->udp 3->icmp
	printf("\n请选择监听的数据包协议类型(0->ip 1->tcp 2->udp 3->icmp) : ");
	scanf("%d",&protocol_type);
	switch(protocol_type)
	{
	case 0:
		strcpy(packet_filter,"ip");
		break;
	case 1:
		strcpy(packet_filter,"ip and tcp");
		break;
	case 2:
		strcpy(packet_filter,"ip and udp");
		break;
	case 3:
		strcpy(packet_filter,"ip and icmp");
		break;
	default:
		break;
	}
	// 编译过滤器
	if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
	{
		fprintf(stderr,"\n不能编译过滤器. 请检测语法.\n");
		// 释放设备列表
		pcap_freealldevs(alldevs);
		return -1;
	}
	
	//设置过滤器
	if (pcap_setfilter(adhandle, &fcode)<0)
	{
		fprintf(stderr,"\n设置过滤器出错.\n");
		pcap_freealldevs(alldevs);
		return -1;
	}
	
	printf("\n在网卡 %s 开始监听...\n", d->description);
	
	// 不再需要任何设备列表,进行释放
	pcap_freealldevs(alldevs);
	
	// 开始嗅探
	pcap_loop(adhandle, 0, packet_handler, NULL);
	
	return 0;
}
Ejemplo n.º 29
0
int
add_or_find_if(pcap_if_t **curdev_ret, pcap_if_t **alldevs, const char *name,
               u_int flags, const char *description, char *errbuf)
{
    pcap_t *p;
    pcap_if_t *curdev, *prevdev, *nextdev;
    int this_instance;

    /*
     * Is there already an entry in the list for this interface?
     */
    for (curdev = *alldevs; curdev != NULL; curdev = curdev->next) {
        if (strcmp(name, curdev->name) == 0)
            break;	/* yes, we found it */
    }

    if (curdev == NULL) {
        /*
         * No, we didn't find it.
         *
         * Can we open this interface for live capture?
         *
         * We do this check so that interfaces that are
         * supplied by the interface enumeration mechanism
         * we're using but that don't support packet capture
         * aren't included in the list.  Loopback interfaces
         * on Solaris are an example of this; we don't just
         * omit loopback interfaces on all platforms because
         * you *can* capture on loopback interfaces on some
         * OSes.
         *
         * On OS X, we don't do this check if the device
         * name begins with "wlt"; at least some versions
         * of OS X offer monitor mode capturing by having
         * a separate "monitor mode" device for each wireless
         * adapter, rather than by implementing the ioctls
         * that {Free,Net,Open,DragonFly}BSD provide.
         * Opening that device puts the adapter into monitor
         * mode, which, at least for some adapters, causes
         * them to deassociate from the network with which
         * they're associated.
         *
         * Instead, we try to open the corresponding "en"
         * device (so that we don't end up with, for users
         * without sufficient privilege to open capture
         * devices, a list of adapters that only includes
         * the wlt devices).
         */
#ifdef __APPLE__
        if (strncmp(name, "wlt", 3) == 0) {
            char *en_name;
            size_t en_name_len;

            /*
             * Try to allocate a buffer for the "en"
             * device's name.
             */
            en_name_len = strlen(name) - 1;
            en_name = malloc(en_name_len + 1);
            if (en_name == NULL) {
                (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
                               "malloc: %s", pcap_strerror(errno));
                return (-1);
            }
            strcpy(en_name, "en");
            strcat(en_name, name + 3);
            p = pcap_open_live(en_name, 68, 0, 0, errbuf);
            free(en_name);
        } else
#endif /* __APPLE */
            p = pcap_open_live(name, 68, 0, 0, errbuf);
        if (p == NULL) {
            /*
             * No.  Don't bother including it.
             * Don't treat this as an error, though.
             */
            *curdev_ret = NULL;
            return (0);
        }
        pcap_close(p);

        /*
         * Yes, we can open it.
         * Allocate a new entry.
         */
        curdev = malloc(sizeof(pcap_if_t));
        if (curdev == NULL) {
            (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
                           "malloc: %s", pcap_strerror(errno));
            return (-1);
        }

        /*
         * Fill in the entry.
         */
        curdev->next = NULL;
        curdev->name = strdup(name);
        if (curdev->name == NULL) {
            (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
                           "malloc: %s", pcap_strerror(errno));
            free(curdev);
            return (-1);
        }
        if (description != NULL) {
            /*
             * We have a description for this interface.
             */
            curdev->description = strdup(description);
            if (curdev->description == NULL) {
                (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
                               "malloc: %s", pcap_strerror(errno));
                free(curdev->name);
                free(curdev);
                return (-1);
            }
        } else {
            /*
             * We don't.
             */
            curdev->description = NULL;
        }
        curdev->addresses = NULL;	/* list starts out as empty */
        curdev->flags = 0;
        if (ISLOOPBACK(name, flags))
            curdev->flags |= PCAP_IF_LOOPBACK;

        /*
         * Add it to the list, in the appropriate location.
         * First, get the instance number of this interface.
         */
        this_instance = get_instance(name);

        /*
         * Now look for the last interface with an instance number
         * less than or equal to the new interface's instance
         * number - except that non-loopback interfaces are
         * arbitrarily treated as having interface numbers less
         * than those of loopback interfaces, so the loopback
         * interfaces are put at the end of the list.
         *
         * We start with "prevdev" being NULL, meaning we're before
         * the first element in the list.
         */
        prevdev = NULL;
        for (;;) {
            /*
             * Get the interface after this one.
             */
            if (prevdev == NULL) {
                /*
                 * The next element is the first element.
                 */
                nextdev = *alldevs;
            } else
                nextdev = prevdev->next;

            /*
             * Are we at the end of the list?
             */
            if (nextdev == NULL) {
                /*
                 * Yes - we have to put the new entry
                 * after "prevdev".
                 */
                break;
            }

            /*
             * Is the new interface a non-loopback interface
             * and the next interface a loopback interface?
             */
            if (!(curdev->flags & PCAP_IF_LOOPBACK) &&
                    (nextdev->flags & PCAP_IF_LOOPBACK)) {
                /*
                 * Yes, we should put the new entry
                 * before "nextdev", i.e. after "prevdev".
                 */
                break;
            }

            /*
             * Is the new interface's instance number less
             * than the next interface's instance number,
             * and is it the case that the new interface is a
             * non-loopback interface or the next interface is
             * a loopback interface?
             *
             * (The goal of both loopback tests is to make
             * sure that we never put a loopback interface
             * before any non-loopback interface and that we
             * always put a non-loopback interface before all
             * loopback interfaces.)
             */
            if (this_instance < get_instance(nextdev->name) &&
                    (!(curdev->flags & PCAP_IF_LOOPBACK) ||
                     (nextdev->flags & PCAP_IF_LOOPBACK))) {
                /*
                 * Yes - we should put the new entry
                 * before "nextdev", i.e. after "prevdev".
                 */
                break;
            }

            prevdev = nextdev;
        }

        /*
         * Insert before "nextdev".
         */
        curdev->next = nextdev;

        /*
         * Insert after "prevdev" - unless "prevdev" is null,
         * in which case this is the first interface.
         */
        if (prevdev == NULL) {
            /*
             * This is the first interface.  Pass back a
             * pointer to it, and put "curdev" before
             * "nextdev".
             */
            *alldevs = curdev;
        } else
            prevdev->next = curdev;
    }

    *curdev_ret = curdev;
    return (0);
}
Ejemplo n.º 30
0
 int main (int argc, char **argv) {
    int opt, err;
    enum { SRC_INVAL, SRC_IFACE, SRC_FILE } pcap_src = SRC_INVAL;
    const char *src_name = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct sigaction sig_exit = {{on_signal}};


    if (sigaction(SIGINT, &sig_exit, NULL) < 0 ||
            sigaction(SIGTERM, &sig_exit, NULL) < 0) {
        perror("sigaction");
        return EXIT_FAILURE;
    }


    while ((opt = getopt(argc, argv, "?hi:r:")) != -1) {
        if (opt == '?' || opt == 'h') {
            show_help_die(argv[0]);
        } else if (!(opt == 'i' || opt == 'r')) {
            fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], opt);
            show_help_die(argv[0]);
        } else if (pcap_src != SRC_INVAL) {
            fprintf(stderr, "%s: duplicate option -- '%c'\n", argv[0], opt);
            show_help_die(argv[0]);
        } else {
            pcap_src = (opt == 'i' ? SRC_IFACE : SRC_FILE);
            src_name = optarg;
        }
    }

    if (pcap_src == SRC_INVAL || optind < argc)
        show_help_die(argv[0]);


    if (pcap_src == SRC_IFACE)
        pif = pcap_open_live(src_name, 16384, 1, 100, errbuf);
    else
        pif = pcap_open_offline(src_name, errbuf);


    if (pif == NULL) {
        fprintf(stderr, "pcap_open: %s\n", errbuf);
        return EXIT_FAILURE;
    }


    if (pcap_set_datalink(pif, DLT_EN10MB) < 0) {
        pcap_perror(pif, "pcap_set_datalink");
        pcap_close(pif);
        return EXIT_FAILURE;
    }


    err = pcap_loop(pif, -1, my_handler, NULL);
    if (err == -1)
        pcap_perror(pif, "pcap_loop");


    pcap_close(pif);
    pif = NULL;


    return err < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}