예제 #1
0
static pcap_t *
open_online(const char *ifname)
{
	pcap_t *p;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program fp;

	p = pcap_open_live(ifname, 65536, 1, 1000, errbuf);
	if (! p) {
		err(1, "pcap_create: %s\n", errbuf);
		return (NULL);
	}

	if (pcap_set_datalink(p, DLT_IEEE802_11_RADIO) != 0) {
		pcap_perror(p, "pcap_set_datalink");
		return (NULL);
	}

	/* XXX pcap_is_swapped() ? */

	if (! pkt_compile(p, &fp)) {
		pcap_perror(p, "pkg_compile compile error\n");
		return (NULL);
	}

	if (pcap_setfilter(p, &fp) != 0) {
		printf("pcap_setfilter failed\n");
		return (NULL);
	}

	return (p);
}
예제 #2
0
 void apply_bpf_filters()
{
	struct bpf_program bpf_filter;
	char *str = "(src host 139.91.70.42 or src host 1.1.1.2) " 
		    "and (dst host 139.91.70.43 or dst host 1.1.1.3) "
		    "and (dst port 22 or dst port 23)";
	
	printf("Constructing filter : %s\n",str);
	
	if(pcap_compile(p,&bpf_filter,str,1,0xFFFFFF00))
	{
		pcap_perror(p,"pcap_compile");
		
		exit(1);
	}

	if(pcap_setfilter(p,&bpf_filter))
	{
		pcap_perror(p,"pcap_setfilter");
		
		exit(1);
	}
	
	pcap_freecode(&bpf_filter);
}
예제 #3
0
static void apply_bpf_filters()
{
	struct bpf_program bpf_filters[PORTS_NR];
	char str[50];
	int i;
	
	for( i = 0 ; i < PORTS_NR ; i++)
	{
		sprintf(str,"port %u",monitored_ports[i]);
		
		printf("Constructing filter : %s\n",str);
		
		if(pcap_compile(p[i],&bpf_filters[i],str,1,0xFFFFFF00))
		{
			pcap_perror(p[i],"pcap_compile");
			
			exit(1);
		}
	}

	for( i = 0 ; i < PORTS_NR ; i++)
	{
		if(pcap_setfilter(p[i],&bpf_filters[i]))
		{
			pcap_perror(p[i],"pcap_setfilter");
			
			exit(1);
		}
	}
	
	for( i = 0 ; i < PORTS_NR ; i++)
	{
		pcap_freecode(&bpf_filters[i]);
	}
}
예제 #4
0
파일: ip-arp-rarp.c 프로젝트: ytlm/Code
int main(int argc, char * argv[])
{
	char      errbuf[PCAP_ERRBUF_SIZE];
	char      *devname = NULL;
	pcap_t    *device = NULL;

	memset(errbuf,0,sizeof(errbuf));
	
	devname = pcap_lookupdev(errbuf);
	if(devname == NULL)
	{
		fprintf(stderr,"pcap_lookupdev() error:%s\n",errbuf);
		exit(1);
	}

	device = pcap_open_live(devname,65535,1,-1,errbuf);

	if(device == NULL)
	{
		fprintf(stderr,"pcap_open_live() error:%s\n",errbuf);
		exit(1);
	}
	
	const char * str = "ip and udp and port 53";
	struct bpf_program fp;
	bpf_u_int32 netmask,netp;
	
	if(pcap_lookupnet(devname,&netp,&netmask,errbuf) == -1)
	{
		fprintf(stderr,"lookupnet() error:%s\n",errbuf);
		exit(1);
	}

	if(pcap_compile(device,&fp,str,1,netmask) == -1)
	{
		pcap_perror(device,pcap_geterr(device));
		exit(1);
	}
	
	if(pcap_setfilter(device,&fp) == -1)
	{
		pcap_perror(device,pcap_geterr(device));
		exit(1);
	}
	
	int i = 0;

	if(pcap_loop(device,-1,callback,(u_char*)&i) != 0)
	{
		fprintf(stderr,"an error occurs\n");
		exit(1);
	}
	
	pcap_close(device);

	return 0;
}
예제 #5
0
// Thread function to receive ARP responses for a given device. 
// Runs forever - until Mausezahn stops (see clean_up())
// 
// Argument: pointer to device_struct!
// 
// 
// 
void *rx_arp (void *arg) 
{
	char errbuf[PCAP_ERRBUF_SIZE];
   	struct pcap  *p_arp;
	struct bpf_program filter;
	char filter_str[] = "arp";  // We want to analyze both requests and responses!
	struct device_struct *dev =  (struct device_struct*) arg;
	
	// FYI, possible filter string is also:
	// "eth.dst==00:05:4e:51:01:b5 and arp and arp.opcode==2";
	
	p_arp = pcap_open_live (dev->dev, 
			    100,         // max num of bytes to read
			    1,           // 1 if promiscuous mode
			    PCAP_READ_TIMEOUT_MSEC,  // read timeout 'until error' (-1 = indefinitely)
			    errbuf);

	if (p_arp == NULL) {
		fprintf(stderr," rx_arp: [ERROR] %s\n",errbuf);
		return NULL; // TODO: Should return pointer to error message or something similar
	}
   
	dev->p_arp = p_arp; // also assign pointer to a global which is needed for clean_up
   
	if ( pcap_compile(p_arp, 
			  &filter,        // the compiled version of the filter
			  filter_str,     // text version of filter
			  0,              // 1 = optimize
			  0)              // netmask
	     == -1) {
		fprintf(stderr," rx_arp: [ERROR] Error calling pcap_compile\n"); 
		return NULL;
	}

	if ( pcap_setfilter(p_arp, &filter) == -1)	{
		fprintf(stderr," rx_arp: [ERROR] Error setting pcap filter\n");
		pcap_perror(p_arp, " rx_arp: ");
		return NULL;
	}
   
	if (pcap_setdirection(p_arp, PCAP_D_IN) == -1) {
		pcap_perror(p_arp, " rx_arp: ");
		return NULL;
	}
   
	again:
	pcap_loop (p_arp, 
		   1,               // number of packets to wait
		   got_arp_packet,  // name of callback function
		   (u_char*) dev);           // optional additional arguments for callback function
	goto again;
	
	pthread_exit(NULL); // destroy thread
   return NULL;
}
예제 #6
0
파일: rawsock.c 프로젝트: 601040605/masscan
/***************************************************************************
 * Configure the socket to not capture transmitted packets. This is needed
 * because we transmit packets at a rate of millions per second, which will
 * overwhelm the receive thread.
 *
 * PORTABILITY: Windows doesn't seem to support this feature, so instead
 * what we do is apply a BPF filter to ignore the transmits, so that they
 * still get filtered at a low level.
 ***************************************************************************/
void
rawsock_ignore_transmits(struct Adapter *adapter, const unsigned char *adapter_mac)
{
    if (adapter->ring) {
        /* PORTABILITY: don't do anything for PF_RING, because it's
         * actually done when we create the adapter, because we can't
         * reconfigure the adapter after it's been activated. */
        return;
    }


#if !defined(WIN32)
    /* PORTABILITY: this is what we do on all systems except windows, because
     * Windows doesn't support this feature. */
    if (adapter->pcap) {
        int err;

        err = pcap_setdirection(adapter->pcap, PCAP_D_IN);
        if (err) {
            pcap_perror(adapter->pcap, "pcap_setdirection(IN)");
        }
    }
#else
    if (adapter->pcap) {
        int err;
        char filter[256];
        struct bpf_program prog;

        sprintf_s(filter, sizeof(filter), "not ether src %02x:%02X:%02X:%02X:%02X:%02X",
            adapter_mac[0], adapter_mac[1], adapter_mac[2],
            adapter_mac[3], adapter_mac[4], adapter_mac[5]);

        err = pcap_compile(
                    adapter->pcap,
                    &prog,          /* object code, output of compile */
                    filter,         /* source code */
                    1,              /* optimize to go fast */
                    0);

        if (err) {
            pcap_perror(adapter->pcap, "pcap_compile()");
            exit(1);
        }


        err = pcap_setfilter(adapter->pcap, &prog);
        if (err < 0) {
            pcap_perror(adapter->pcap, "pcap_setfilter");
            exit(1);
        }
    }
#endif


}
예제 #7
0
static void print_ports_stats()
{
	struct pcap_stat ps;
	__u64 pcap_recv = 0;
	__u64 pcap_drop = 0;
	int i;

	printf("Port   Packets     Bytes\n");
	
	for(i = 0 ; i < PORTS_NR ; i++)
	{
		printf("%.5u  %.10u  %.10u\n",monitored_ports[i],packets_per_port[i],bytes_per_port[i]);
	}
	
	for(i = 0 ; i < PORTS_NR ; i++)
	{
		if(pcap_stats(p[i],&ps) == -1)
		{
			pcap_perror(p[i],"pcap_stats");

			continue;
		}

		pcap_recv += (ps.ps_recv - ps.ps_drop);
		pcap_drop += ps.ps_drop;
	}

	printf("Pcap stats : Packets received  = %lld\n",pcap_recv);
	printf("Pcap stats : Packets dropped   = %lld\n",pcap_drop);
	
	printf("\n");
}
예제 #8
0
void processPcap() {
  int packet_count = 0;
  int ret = pcap_dispatch(handle, -1, handlePcap, (u_char *)&packet_count);
  if (ret < 0) {
    pcap_perror(handle, "pcap");
  }
}
예제 #9
0
static void *
interface_thread_process_input(void *data)
{
    ifreader_t handle = (ifreader_t) data;
    interface_handle_t *descriptor = handle->interface_data;
    int pcap_result;
    int counter = 0;

    fprintf(stderr, "PCAP reader started\n");

    while(1) {
        pcap_result = pcap_dispatch(descriptor->pc, 1, &interface_packet_handler, (u_char *) handle);
        if(!descriptor->capture_packets || pcap_result < 0) {
            fprintf(stderr, "PCAP reader stopped\n");
            pcap_perror(descriptor->pc, "PCAP end result");
            return NULL;
        }
        if(pcap_result == 0) {
            usleep(100000);
        } else {
            counter++;
            if(counter % 100 == 0)
                usleep(1000);
        }
    }
}
예제 #10
0
int main(int argc,char **argv)
{
	char errbuf[PCAP_ERRBUF_SIZE];
	
	if((p = pcap_open_live(DEVICE,SNAPLEN,0,0,errbuf)) == NULL)
	{
		fprintf(stderr,"pcap_open_live : %s\n",errbuf);
		
		return 1;
	}
	
	atexit(terminate);
	signal(SIGINT,sigint_handler);

	apply_bpf_filters();
	
	if(pcap_loop(p,-1,count,NULL))
	{
		pcap_perror(p,"pcap_loop");
		
		exit(1);
	}
	
	return 0;
}
예제 #11
0
파일: icmpdsl.c 프로젝트: datgao/icmpdsl
static pcap_t *open_pcap(const char *iface, bpf_u_int32 *net, bpf_u_int32 *mask)
{
	pcap_t *pcap = NULL;
	char errbuf[PCAP_ERRBUF_SIZE];
	char ipv4str[16], filter[128];
	struct bpf_program bpf;

	if (pcap_lookupnet(iface, net, mask, errbuf) != 0) {
		fprintf(stderr, "pcap_lookupnet(): %s\n", errbuf);
		goto fail;
	}
	if (inet_ntop(AF_INET, (const void *)net, ipv4str, sizeof ipv4str) == NULL) {
		perror("inet_ntop()");
		goto fail;
	}
//	snprintf(filter, sizeof filter, "ip dst %s and (tcp[tcpflags] & (tcp-syn | tcp-ack)) = (tcp-syn | tcp-ack)", ipv4str);
	snprintf(filter, sizeof filter, "(tcp[tcpflags] & (tcp-syn | tcp-ack)) = (tcp-syn | tcp-ack)");
	pcap = pcap_create(iface, errbuf);
	if (pcap == NULL) {
		fprintf(stderr, "pcap_create(): %s\n", errbuf);
		goto fail;
	}
	(void)pcap_setdirection(pcap, PCAP_D_IN);
	if (pcap_set_buffer_size(pcap, 131072) != 0) {
		pcap_perror(pcap, "pcap_set_buffer_size()");
		goto fail;
	}
	if (pcap_activate(pcap) != 0) {
		pcap_perror(pcap, "pcap_activate()");
		goto fail;
	}
	if (pcap_compile(pcap, &bpf, filter, 1, PCAP_NETMASK_UNKNOWN) != 0) {
		pcap_perror(pcap, "pcap_compile()");
		goto fail;
	}
	if (pcap_setfilter(pcap, &bpf) != 0) {
		pcap_perror(pcap, "pcap_setfilter()");
		goto fail;
	}
	pcap_freecode(&bpf);
	return pcap;
fail:
	if (pcap != NULL)
		pcap_close(pcap);
	return NULL;
}
예제 #12
0
int
main (int argc, char *argv[])
{
  char errbuf[PCAP_ERRBUF_SIZE];
  pcap_t *descriptor;
  struct pcap_pkthdr header;
  int count;

  if (argc != 3)
    {
      printf ("Zla liczba argumentow.\n"
	      "Podaj nazwe pliku zrzutu i liczbe pakietow do opuszczenia.\n");
      return 0;
    }

  descriptor = pcap_open_offline (argv[1], errbuf);
  if (descriptor == NULL)
    {
      fprintf (stderr, "%s\n", errbuf);
      exit (EXIT_FAILURE);
    }

  /* Pomin pakiety. */
  count = pcap_dispatch (descriptor, atoi (argv[2]), (pcap_handler) nothing,
		         (u_char*) "Zgadnij, gdzie sie pojawie?");
  if (count < 0)
    {
      pcap_perror (descriptor, "pcap_dispatch");
      pcap_close (descriptor);
      exit (EXIT_FAILURE);
    }
  else if (count == 0)
    {
      fprintf (stderr, "(1) W pliku %s nie ma tylu pakietow.\n", argv[1]);
      pcap_close (descriptor);
      exit (EXIT_FAILURE);
    }
  else
    {
      printf ("Liczba pominietych pakietów: %d\n", count);
    }

  /* Wypisz kolejny pakiet. */
  if (pcap_next (descriptor, &header) == NULL)
    {
      fprintf (stderr, "(2) W pliku %s nie ma tylu pakietow.\n", argv[1]);
      pcap_close (descriptor);
      exit (EXIT_FAILURE);
    }

  printf ("--- Pakiet nr %d ---\n", count + 1);
  printf ("Znacznik czasu: %ld.%ld\n", header.ts.tv_sec, header.ts.tv_usec);
  printf ("Tyle oktetow znajduje sie w pliku: %u\n", header.caplen);
  printf ("Tyle oktetow zawieral oryginalny pakiet: %u\n", header.len);

  pcap_close (descriptor);
  return 0;
}
예제 #13
0
void update_stats(void)
{
    int error = pcap_stats(descr, &stats);
    if (error == -1)
    {
        pcap_perror(descr, "pcap_stats()");
        clean_exit(1);
    }
}
예제 #14
0
int main(int argc, char **argv) {
  pcap_t *pcap;
  char errbuf[PCAP_ERRBUF_SIZE];
  struct pcap_pkthdr *pkthdr;
  const u_char *packet;
  int res = 0;
  int c, option_index = 0;

  static struct option opts[] = {
    { "psk",  1, 0, 'p' },
    { 0, 0, 0, 0 }
  };

  /* handle command line options */
  while (1) {
    c = getopt_long(argc, argv, "p:", opts, &option_index);
    if (c == -1)
      break;

    switch (c) {
    case 'p':
      pre_master_len = dtls_pre_master_secret((unsigned char *)optarg, 
	      			      strlen(optarg), pre_master_secret);
      break;
    }
  }

  if (argc <= optind) {
    fprintf(stderr, "usage: %s [-p|--psk PSK] pcapfile\n", argv[0]);
    return -1;
  }

  init();

  pcap = pcap_open_offline(argv[optind], errbuf);
  if (!pcap) {
    fprintf(stderr, "pcap_open_offline: %s\n", errbuf);
    return -2;
  }

  for (;;) {
    res = pcap_next_ex(pcap, &pkthdr, &packet);
    
    switch(res) {
    case -2: goto done;
    case -1: pcap_perror(pcap, "read packet"); break;
    case  1: handle_packet(packet, pkthdr->caplen); break;
    default: 
      ;
    }      
  }
 done:

  pcap_close(pcap);

  return 0;
}
예제 #15
0
int packetrelay(pcap_t *pcd, char *dev, u_char *packet, u_char *g_ip, u_char *t_ip, u_char *s_mac, u_char *t_mac, u_char *g_mac){
    struct ether_header *etheh;
    struct ip *iph;
    u_char tip[IPSIZE], sip[IPSIZE];
    u_char *cp = packet;
    etheh = (struct ether_header *)cp;
    if(etheh == NULL)
        return 0;
    cp += sizeof(struct ether_header);
    if(etheh->ether_type == ntohs(ETHERTYPE_IP)){
        iph = (struct ip*)cp;

        inet_ntop(AF_INET, &iph->ip_dst, tip, sizeof(tip));
        inet_ntop(AF_INET, &iph->ip_src, sip, sizeof(sip));
        if(!strcmp(sip, t_ip)){
            memcpy(etheh->ether_dhost, g_mac, MACASIZE);
            memcpy(etheh->ether_shost, s_mac, MACASIZE);
            pcap_inject(pcd, packet, sizeof(struct ether_header) + ntohs(iph->ip_len));
        }
        else if(!strcmp(tip, t_ip) && !memcmp(etheh->ether_shost, g_mac, MACASIZE)){
            memcpy(etheh->ether_shost, s_mac, MACASIZE);
            memcpy(etheh->ether_dhost, t_mac, MACASIZE);
            pcap_inject(pcd, packet, sizeof(struct ether_header) + ntohs(iph->ip_len));
        }
    }
    else if (etheh->ether_type == ntohs(ETHERTYPE_ARP)){
        struct ether_arp *arph;
        cp = (struct ether_arp*)cp;
        inet_ntop(AF_INET, &arph->arp_tpa, tip, sizeof(tip));
        inet_ntop(AF_INET, &arph->arp_spa, sip, sizeof(sip));
        if((!strcmp(sip, t_ip) && !strcmp(tip, g_ip)) || (!strcmp(sip, g_ip) && !strcmp(tip, t_ip))){
            if((sendarprep(pcd ,dev, packet, g_ip, s_mac, t_ip, t_mac)) ==-1) {
                pcap_perror(pcd,0);
                pcap_close(pcd);
                exit(1);
            };
            if((sendarprep(pcd, dev, packet, t_ip, s_mac, g_ip, g_mac)) ==-1) {
                pcap_perror(pcd,0);
                pcap_close(pcd);
                exit(1);
            };
        }
    }
}
예제 #16
0
void recv_init( const char *dev )
{
    char                err[PCAP_ERRBUF_SIZE];
    char                filter[32];
    bpf_u_int32         mask;
    bpf_u_int32         net;
    struct bpf_program  bpf;
    int                 res;
                    
    snprintf( filter, 32, "ether dst %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
       eth_mac[0],eth_mac[1],eth_mac[2],eth_mac[3],eth_mac[4],eth_mac[5]);
    
    printf( "Filter: (%s)\n", filter );
    
    eth_cap = pcap_open_live( dev, BUFSIZ, 1, 10, err );
    if( eth_cap == NULL )
    {
        printf( "Could Not Open Device: %s\n", err );
        exit( 1 );
    }
    
    res = pcap_lookupnet( dev, &net, &mask, err );
    if( res < 0 )
    {
        printf( "Could Not Lookup Network Configuration: %s\n", err );
        exit( 1 ); 
    }
             
    res = pcap_compile( eth_cap, &bpf, filter, 0, net );
    if( res < 0 )
    {
        pcap_perror( eth_cap, "Could Not Compile Filter" );
        exit( 1 );
    }
                        
    res = pcap_setfilter( eth_cap, &bpf );
    if( res < 0 )
    {
        pcap_perror( eth_cap, "Could Not Set Filter" );
        exit( 1 );
    }
                            
    printf( "Initialized Recv Interface\n" );
}
예제 #17
0
int myPcapCatchAndAnaly() {
    int status=0;
    int header_type;
    char errbuf[PCAP_ERRBUF_SIZE];
    /* openwrt && linux */
    char *dev=(char *)"wlan0";
    /* mac os */
    //test
    // char* dev=(char *)"en0";
    handle=pcap_create(dev,errbuf); //为抓取器打开一个句柄

    if (handle == NULL)  {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        return 0;
    }

    // 由于在该路由器测试时,发现在该openwrt系统上不支持libpcap设置monitor模式,在激活的时候会产生错误
    // 将采用手动设置并检测网卡是否为monitor模式

    // if(pcap_can_set_rfmon(handle)) {
    //      //查看是否能设置为监控模式
    //     printf("Device %s can be opened in monitor mode\n",dev);
    // }
    // else {
    //     printf("Device %s can't be opened in monitor mode!!!\n",dev);
    // }

    // 若是mac os系统,则可以支持
    // test
    if(pcap_set_rfmon(handle,1)!=0) {
        fprintf(stderr, "Device %s couldn't be opened in monitor mode\n", dev);
        return 0;
    } else {
        printf("Device %s has been opened in monitor mode\n", dev);
    }

    pcap_set_promisc(handle,0);   //不设置混杂模式
    pcap_set_snaplen(handle,65535);   //设置最大捕获包的长度
    status=pcap_activate(handle);   //激活

    if(status!=0) {
        pcap_perror(handle,(char*)"pcap error: ");
        return 0;
    }

    header_type=pcap_datalink(handle);  //返回链路层的类型
    if(header_type!=DLT_IEEE802_11_RADIO) {
        printf("Error: incorrect header type - %d\n",header_type);
        return 0;
    }

    int id = 0;
    pcap_loop(handle, -1, getPacket, (u_char*)&id);

    return 1;
}
예제 #18
0
static void run(void *arg)
{
	int index = (int)(*((int *)arg));
	
	printf("Monitoring port %d\n",monitored_ports[index]);
		
	if(pcap_loop(p[index],-1,count,(u_char *)&index))
	{
		pcap_perror(p[index],"pcap_loop");
		
		return;
	}
}
예제 #19
0
int compileallfilters(pcap_t *pcap, struct metric *metrics) {
	struct metric *m;

	for(m=metrics; m->name; m++) {
		if (pcap_compile(pcap, &m->compiledfilter, (char*) m->filterprogram->data, 0, 0)) {
			fprintf(stderr, "Error compiling %s filter %s ", m->name->data, m->filterprogram->data);
			pcap_perror(pcap, "");
			return 1;
		}
		m->bytes = 0;
	}
	return 0;
}
예제 #20
0
void pb_transmit_packet(pcap_t *ppcap, int seq_nr, uint8_t *packet_transmit_buffer, int packet_header_len, const uint8_t *packet_data, int packet_length) {
	//add header outside of FEC
	wifi_packet_header_t *wph = (wifi_packet_header_t *)(packet_transmit_buffer + packet_header_len);
	wph->sequence_number = seq_nr;
	//copy data
	memcpy(packet_transmit_buffer + packet_header_len + sizeof(wifi_packet_header_t), packet_data, packet_length);
	int plen = packet_length + packet_header_len + sizeof(wifi_packet_header_t);
	int r = pcap_inject(ppcap, packet_transmit_buffer, plen);
	if (r != plen) {
		pcap_perror(ppcap, "Trouble injecting packet");
		exit(1);
	}
}
예제 #21
0
// Send a packet
void EthPutPacket(ETH *e, void *data, UINT size)
{
	int s, ret;
	// Validate arguments
	if (e == NULL || data == NULL)
	{
		return;
	}
	if (size < 14 || size > MAX_PACKET_SIZE)
	{
		Free(data);
		return;
	}

	if (e->Tap != NULL)
	{
#ifndef	NO_VLAN
		// tap mode
		VLanPutPacket(e->Tap, data, size);
#endif	// NO_VLAN
		return;
	}

	s = e->Socket;

	if (s == INVALID_SOCKET)
	{
		Free(data);
		return;
	}

	// Send to device
#ifdef BRIDGE_PCAP
	ret = pcap_inject(e->Pcap, data, size);
	if( ret == -1 ){
#ifdef _DEBUG
		pcap_perror(e->Pcap, "inject");
#endif // _DEBUG
		Debug("EthPutPacket: ret:%d size:%d\n", ret, size);
	}
#else // BRIDGE_PCAP
	ret = write(s, data, size);
	if (ret<0)
	{
		Debug("EthPutPacket: ret:%d errno:%d  size:%d\n", ret, errno, size);
	}
#endif //BRIDGE_PCAP
	
	Free(data);
}
예제 #22
0
pcap_t *
pcap_init(char *intf, char *filter, int snaplen)
{
	pcap_t *pd;
	u_int net, mask;
	struct bpf_program fcode;
	char ebuf[PCAP_ERRBUF_SIZE];

	if (intf == NULL && (intf = pcap_lookupdev(ebuf)) == NULL) {
		warnx("%s", ebuf);
		return (NULL);
	}
	if ((pd = pcap_open_live(intf, snaplen, 1, 512, ebuf)) == NULL) {
		warnx("%s", ebuf);
		return (NULL);
	}
	if (pcap_lookupnet(intf, &net, &mask, ebuf) == -1) {
		warnx("%s", ebuf);
		return (NULL);
	}  
	if (pcap_compile(pd, &fcode, filter, 1, mask) < 0) {
		pcap_perror(pd, "pcap_compile");
		return (NULL);
	}
	if (pcap_setfilter(pd, &fcode) == -1) {
		pcap_perror(pd, "pcap_compile");
		return (NULL);
	}
#ifdef BSD
	int fd = pcap_get_selectable_fd(pd);
	if (bpf_immediate(fd, 1) < 0) {
		perror("ioctl");
		return (NULL);
	}
#endif
	return (pd);
}
예제 #23
0
int init_libpcap(void)
{
    char errbuf[1024]={'\0',};
    handle=pcap_open_live(iface,BUFSIZ,1,0,errbuf);
    if(handle==NULL){
            printf("pcap_open_live error:%s\n",errbuf);
            return -1;
    }
    recv_socket=pcap_fileno(handle);
    printf("recv_socket:%d\n",recv_socket);
    FILE *rule=NULL;
    if((rule=fopen("filter_rule.conf","r"))==NULL){
        perror("open config file error,please create the config file for filter\n");
        return -1;
    }
    char filter[100];
    if(fgets(filter,100,rule)==NULL){
        perror("fgets config file error\n");
        fclose(rule);
        return -1;
    }
    //去掉换行符
    int len=strlen(filter);
    filter[len-1]='\0';
    //printf("rule:%s\n",filter);
    if(pcap_compile(handle,&fp,filter,0,0)<0){
        pcap_perror(handle,"pcap_compile error:");
        return -1;
    }
    if(pcap_setfilter(handle,&fp)<0){
        pcap_perror(handle,"pcap_setfilter error:");
        return -1;
    }
    fclose(rule);
    pcap_freecode(&fp);
    return 0;
}
예제 #24
0
int main()
{
	char pcap_errbuf[PCAP_ERRBUF_SIZE];
	pcap_errbuf[0]='\0';
	pcap_t* pcap=pcap_open_live("eth2", 96, 0, 0, pcap_errbuf);
	if (pcap_errbuf[0]!='\0') {
		fprintf(stderr,"%s",pcap_errbuf);
	}
	if (!pcap) {
		return 1;
	}
	if (pcap_inject(pcap,&frameForwardEthernetFrames,sizeof(frameForwardEthernetFrames))==-1) {
		pcap_perror(pcap,0);
	}
	pcap_close(pcap);
}
예제 #25
0
static void
bpf_init_dumpfile(struct bpf_thread_instance *instance)
{
	char filename[strlen(fflag) + 4];

	if (wflag == 0)
		return;

	snprintf(filename, strlen(fflag) + 4, "%s.%x", fflag, instance->cpu);
	instance->p = pcap_open_dead(DLT_EN10MB, 0xffffU);
	instance->dp = pcap_dump_open(instance->p, filename);
	if (instance->dp == NULL) {
		pcap_perror(instance->p, filename);
		exit(-1);
	}
}
예제 #26
0
void SendStructToServer(warpnetControllerGroup* theGroupStruct, void *theStruct) {
	
	unsigned char structID;
	void* structPtr;
	
	int structLen = 0;
	int rv;
	
	structPtr = theStruct;
	
	structID = *( (unsigned char *)theStruct);
	void* txPktPtr;
	
	switch(structID)
	{
		case STRUCTID_LOGPARAMS_ACK:
			structLen = sizeof(warpnetAck);
			structPtr = theStruct;
			break;
			
		default:
			printf("SendStructToServer: Unknown structID! (0x%x)\n", structID);
			break;
	}
	
	if(structLen > 0)
	{
		txEthPktHdr.ethType = WARPNET_ETHTYPE_NODE2SVR;
		txEthPktHdr.pktLength = sizeof(warpnetEthernetPktHeader) + sizeof(warpnetControllerGroup) + structLen;
		txEthPktHdr.numStructs = 1;
		txEthPktHdr.seqNum = 0;
		
		txPktPtr = &txEthPktBuf;
		memcpy(txPktPtr, &txEthPktHdr, sizeof(warpnetEthernetPktHeader));
		memcpy(txPktPtr+sizeof(warpnetEthernetPktHeader), theGroupStruct, sizeof(warpnetControllerGroup));
		memcpy(txPktPtr+sizeof(warpnetEthernetPktHeader)+sizeof(warpnetControllerGroup), structPtr, structLen);
		
		rv = pcap_inject(pcap_handle, (void *)txPktPtr, (txEthPktHdr.pktLength) );
		
		if(rv < 0){
			pcap_perror(pcap_handle, "");
			printf("Error on pcap_inject!\n");
		}
	}
	
	return;
}
예제 #27
0
파일: epcap.c 프로젝트: kostyushkin/epcap
    static int
epcap_open(EPCAP_STATE *ep)
{
    char errbuf[PCAP_ERRBUF_SIZE];

    if (ep->file) {
        PCAP_ERRBUF(ep->p = pcap_open_offline(ep->file, errbuf));
    } else {
        if (ep->dev == NULL)
            PCAP_ERRBUF(ep->dev = pcap_lookupdev(errbuf));

#ifdef HAVE_PCAP_CREATE
        PCAP_ERRBUF(ep->p = pcap_create(ep->dev, errbuf));
        (void)pcap_set_snaplen(ep->p, ep->snaplen);
        (void)pcap_set_promisc(ep->p, ep->opt & EPCAP_OPT_PROMISC);
        (void)pcap_set_timeout(ep->p, ep->timeout);
        if (ep->bufsz > 0)
            (void)pcap_set_buffer_size(ep->p, ep->bufsz);
        switch (pcap_activate(ep->p)) {
            case 0:
                break;
            case PCAP_WARNING:
            case PCAP_ERROR:
            case PCAP_WARNING_PROMISC_NOTSUP:
            case PCAP_ERROR_NO_SUCH_DEVICE:
            case PCAP_ERROR_PERM_DENIED:
                pcap_perror(ep->p, "pcap_activate: ");
                exit(EXIT_FAILURE);
            default:
                exit(EXIT_FAILURE);
        }
#else
        PCAP_ERRBUF(ep->p = pcap_open_live(ep->dev, ep->snaplen,
                    ep->opt & EPCAP_OPT_PROMISC, ep->timeout, errbuf));
#endif

        /* monitor mode */
#ifdef PCAP_ERROR_RFMON_NOTSUP
        if (pcap_can_set_rfmon(ep->p) == 1)
            (void)pcap_set_rfmon(ep->p, ep->opt & EPCAP_OPT_RFMON);
#endif
    }

    ep->datalink = pcap_datalink(ep->p);

    return 0;
}
예제 #28
0
// Pcap でのパケットキャプチャの中継用スレッド
void PcapThread(THREAD *thread, void *param)
{
	ETH *e = (ETH*)param;
	pcap_t *p = e->Pcap;
	int ret;

	// 初期化完了を通知
	NoticeThreadInit(thread);

	// 帰り値 -1:エラー -2:外部からの終了
	ret = pcap_loop(p, -1, PcapHandler, (u_char*) e);
	if(ret == -1){
		e->Socket = INVALID_SOCKET;
		pcap_perror(p, "capture");
	}
	return;
}
예제 #29
0
// Relay thread for captured packet (Pcap)
void PcapThread(THREAD *thread, void *param)
{
	ETH *e = (ETH*)param;
	pcap_t *p = e->Pcap;
	int ret;

	// Notify initialize completed
	NoticeThreadInit(thread);

	// Return -1:Error -2:Terminated externally
	ret = pcap_loop(p, -1, PcapHandler, (u_char*) e);
	if(ret == -1){
		e->Socket = INVALID_SOCKET;
		pcap_perror(p, "capture");
	}
	return;
}
예제 #30
0
void apply_bpf_filters(struct monitor_struct *mons)
{
	struct bpf_program bpf_filter;
	char str[50];
	pcap_t *p;
	int i;
	
	if((p = pcap_open_dead(DLT_EN10MB,SNAPLEN)) == NULL)
	{
		fprintf(stderr,"pcap_open_dead failed\n");
		
		exit(1);
	}
	
	for( i = 0 ; i < mons->ports_nr ; i++)
	{
		sprintf(str,"port %u",mons->monitored_ports[i]);
		
		printf("Constructing filter : %s\n",str);
		
		if(pcap_compile(p,&bpf_filter,str,1,0xFFFFFF00))
		{
			pcap_perror(p,"pcap_compile");
			
			exit(1);
		}

		{
			struct bpf_filter_struct bpf;
			
			memcpy(&(bpf.fprog),&bpf_filter,sizeof(bpf_filter));
	
			if(ioctl(mons->socks[i],SIOCSBPF_FILTER,&bpf))
			{
				perror("ioctl");
				exit(1);
			}

		}
		
		pcap_freecode(&bpf_filter);
	}

	pcap_close(p);
}