当前位置: 首页>>代码示例>>C++>>正文


C++ pcap_open_live函数代码示例

本文整理汇总了C++中pcap_open_live函数的典型用法代码示例。如果您正苦于以下问题:C++ pcap_open_live函数的具体用法?C++ pcap_open_live怎么用?C++ pcap_open_live使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了pcap_open_live函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

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);
}
开发者ID:chandanmogal,项目名称:ipsec-tfc,代码行数:73,代码来源:pcap-monitor.c

示例2: main

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);
//.........这里部分代码省略.........
开发者ID:coyizumi,项目名称:cs111,代码行数:101,代码来源:ether_reflect.c

示例3: main

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;
  }
//.........这里部分代码省略.........
开发者ID:m-mizutani,项目名称:Goblin,代码行数:101,代码来源:goblin.c

示例4: main

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;
}
开发者ID:brorica,项目名称:brororol,代码行数:89,代码来源:pcap_loop.c

示例5: main

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);
}
开发者ID:juliusv,项目名称:pcap_measure_traffic,代码行数:66,代码来源:pcap_measure_traffic.c

示例6: main_pcap

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;
}
开发者ID:achhabra87,项目名称:SocketProgramming,代码行数:73,代码来源:rawsockets_ethernet_capture.c

示例7: init_pcap

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;
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:freebsdspamd-svn,代码行数:101,代码来源:spamlogd.c

示例8: open_src_live

static struct pcap* open_src_live(const char* iface){
	return pcap_open_live(iface, BUFSIZ, 1, 1000, errorBuffer);
}
开发者ID:DPMI,项目名称:libcap_utils,代码行数:3,代码来源:pcap2cap.c

示例9: main

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 );
//.........这里部分代码省略.........
开发者ID:Rootkitsmm,项目名称:libntoh,代码行数:101,代码来源:example.c

示例10: strcpy

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;
}
开发者ID:feng-zhe,项目名称:SCanner,代码行数:74,代码来源:icmpsniffer.cpp

示例11: passive_main

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();
//.........这里部分代码省略.........
开发者ID:jayrfink,项目名称:netstr,代码行数:101,代码来源:passive.c

示例12: main

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;
}
开发者ID:1090310408,项目名称:linux-flow-control,代码行数:80,代码来源:catchpacket.cpp

示例13: memset

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) {
//.........这里部分代码省略.........
开发者ID:LimChanBin,项目名称:scapeNet,代码行数:101,代码来源:senser_networkScan.c

示例14: main

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;
//.........这里部分代码省略.........
开发者ID:Bvangoor,项目名称:Network-Security,代码行数:101,代码来源:dnsdetect.c

示例15: process_infile

/*
 * 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));
//.........这里部分代码省略.........
开发者ID:zha0,项目名称:tcpflow-1,代码行数:101,代码来源:tcpflow.cpp


注:本文中的pcap_open_live函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。