• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ pcap_geterr函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: RotateFile

void RotateFile (pcapfile_t *pcapfile, time_t t_CloseRename, int live)
{
	struct pcap_stat p_stat;
	void *_b;

	dbg_printf ("RotateFile() time: %s\n", UNIX2ISO (t_CloseRename));
	// make sure, alternate buffer is already flushed
	pthread_mutex_lock (&pcapfile->m_pbuff);
	while (pcapfile->alternate_size) {
		pthread_cond_wait (&pcapfile->c_pbuff, &pcapfile->m_pbuff);
	}

	// swap buffers
	_b = pcapfile->data_buffer;
	pcapfile->data_buffer = pcapfile->alternate_buffer;
	pcapfile->data_ptr = pcapfile->data_buffer;
	pcapfile->alternate_buffer = _b;
	pcapfile->alternate_size = pcapfile->data_size;
	pcapfile->t_CloseRename = t_CloseRename;

	// release mutex and signal thread
	pthread_mutex_unlock (&pcapfile->m_pbuff);
	pthread_cond_signal (&pcapfile->c_pbuff);

	pcapfile->data_size = 0;

	if (live) {
		// not a capture file
		if (pcap_stats (pcapfile->p, &p_stat) < 0) {
			LogError ("pcap_stats() failed: %s", pcap_geterr (pcapfile->p));
		} else {
			LogInfo ("Packets received: %u, dropped: %u, dropped by interface: %u ",
			         p_stat.ps_recv, p_stat.ps_drop, p_stat.ps_ifdrop);
		}
	}

} // End of RotateFile
开发者ID:exaexa,项目名称:nfdump,代码行数:37,代码来源:pcaproc.c


示例2: foreach

void CompiledFilterOutput::compileFilter()
{
    struct bpf_program fcode;

    foreach (QString interfaces, intList_) {
        for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) {
            interface_t device = g_array_index(global_capture_opts.all_ifaces, interface_t, i);

            if (interfaces.compare(device.display_name)) {
                continue;
            } else {
                pcap_t *pd = pcap_open_dead(device.active_dlt, WTAP_MAX_PACKET_SIZE);
                g_mutex_lock(pcap_compile_mtx);
                if (pcap_compile(pd, &fcode, compile_filter_.toUtf8().constData(), 1, 0) < 0) {
                    compile_results.insert(interfaces, QString("%1").arg(g_strdup(pcap_geterr(pd))));
                    g_mutex_unlock(pcap_compile_mtx);
                    ui->interfaceList->addItem(new QListWidgetItem(QIcon(":expert/expert_error.png"),interfaces));
                } else {
                    GString *bpf_code_dump = g_string_new("");
                    struct bpf_insn *insn = fcode.bf_insns;
                    int ii, n = fcode.bf_len;
                    gchar *bpf_code_str;
                    for (ii = 0; ii < n; ++insn, ++ii) {
                        g_string_append(bpf_code_dump, bpf_image(insn, ii));
                        g_string_append(bpf_code_dump, "\n");
                    }
                    bpf_code_str = g_string_free(bpf_code_dump, FALSE);
                    g_mutex_unlock(pcap_compile_mtx);
                    compile_results.insert(interfaces, QString("%1").arg(g_strdup(bpf_code_str)));
                    ui->interfaceList->addItem(new QListWidgetItem(interfaces));
                }
                break;
            }
        }
    }
}
开发者ID:vathpela,项目名称:wireshark,代码行数:36,代码来源:compiled_filter_output.cpp


示例3: main

int main(int argc, char** argv)
{       
    char *dev, *error_openoffline, *fname, *gen_error;
    pcap_t *desc;//declaring the decsriptor 
    pcap_dumper_t   *pd;
    struct pcap_pkthdr *header;//declaring packet header
    u_char *sp;//packet data written to savefile    

    dev="eth1";//setting the device as eth1
    fname=argv[1];

    desc=pcap_open_offline( fname, error_openoffline );
    if( desc == NULL )
    {
        printf("The session could not open as %s", error_openoffline );         
        exit(1);
    }

    pd=pcap_dump_open( desc, fname );
    if( pd == NULL )
    {       gen_error=pcap_geterr( desc );
        printf( "\nThe dump could not be opened as %s", gen_error );
        exit(1);        
    }

    pcap_dump( (u_char *) pd, header, sp);

    printf("\nThe data is %h", sp );
    printf("\nThe data is %s", sp );

    pcap_dump_close( pd );
    pcap_close( desc );

    return 0;

}
开发者ID:obscure76,项目名称:csce665,代码行数:36,代码来源:test.c


示例4: load_plugin_filters

void load_plugin_filters(int link_type)
{
  struct plugins_list_entry *list = plugins_list;

  while (list) {
    if ((*list->type.func)) {

      /* compiling aggregation filter if needed */
      if (list->cfg.a_filter) {
	pcap_t *dev_desc;
	bpf_u_int32 localnet, netmask = 0;  /* pcap library stuff */
	char errbuf[PCAP_ERRBUF_SIZE], *count_token;
	int idx = 0;

	dev_desc = pcap_open_dead(link_type, 128); /* 128 bytes should be long enough */

	if (config.dev) pcap_lookupnet(config.dev, &localnet, &netmask, errbuf);

	list->cfg.bpfp_a_table[idx] = malloc(sizeof(struct bpf_program));
	while ( (count_token = extract_token(&list->cfg.a_filter, ',')) && idx < AGG_FILTER_ENTRIES ) {
	  if (pcap_compile(dev_desc, list->cfg.bpfp_a_table[idx], count_token, 0, netmask) < 0) {
	    Log(LOG_WARNING, "WARN: %s\nWARN ( %s/%s ): aggregation filter disabled.\n",
	    				pcap_geterr(dev_desc), list->cfg.name, list->cfg.type);
	  }
	  else {
	    idx++;
	    list->cfg.bpfp_a_table[idx] = malloc(sizeof(struct bpf_program));
	  }
	}

	list->cfg.bpfp_a_num = idx;
      }
    }
    list = list->next;
  }
}
开发者ID:tacgomes,项目名称:pmacct,代码行数:36,代码来源:plugin_hooks.c


示例5: PyErr_SetString

static PyObject *ppcap_set_snaplen(ppcap *self,
                                   PyObject *args)
{
    int snaplen;
    int retval;

    if (!PyArg_ParseTuple(args, "i", &snaplen))
        return NULL;
    if (!ppcap_isset_handle(self->handle)) {
        PyErr_SetString(PyExc_Ppcap, "pcap handle is not created");
        return NULL;
    }
    if (snaplen < MIN_SNAPLEN) {
        PyErr_Format(PyExc_Ppcap, "snaplen must be >= %d",
                     MIN_SNAPLEN);
        return NULL;
    }
    retval = pcap_set_snaplen(self->handle, snaplen);
    if (retval == PCAP_ERROR_ACTIVATED) {
        PyErr_Format(PyExc_Ppcap, "%s", pcap_geterr(self->handle));
        return NULL;
    }
    Py_RETURN_NONE;
}
开发者ID:Magnus9,项目名称:_packet,代码行数:24,代码来源:ppcap.c


示例6: edrv_sendTxBuffer

//------------------------------------------------------------------------------
tOplkError edrv_sendTxBuffer(tEdrvTxBuffer* pBuffer_p)
{
    int         pcapRet;

    // Check parameter validity
    ASSERT(pBuffer_p != NULL);

    //TRACE("%s: TxB=%p (%02X), last TxB=%p\n", __func__, pBuffer_p, (UINT)pBuffer_p->pBuffer[5], edrvInstance_l.pTransmittedTxBufferLastEntry);

    if (pBuffer_p->txBufferNumber.pArg != NULL)
        return kErrorInvalidOperation;

    EnterCriticalSection(&edrvInstance_l.criticalSection);
    if (edrvInstance_l.pTransmittedTxBufferLastEntry == NULL)
    {
        edrvInstance_l.pTransmittedTxBufferLastEntry =
            edrvInstance_l.pTransmittedTxBufferFirstEntry = pBuffer_p;
    }
    else
    {
        edrvInstance_l.pTransmittedTxBufferLastEntry->txBufferNumber.pArg = pBuffer_p;
        edrvInstance_l.pTransmittedTxBufferLastEntry = pBuffer_p;
    }
    LeaveCriticalSection(&edrvInstance_l.criticalSection);

    pcapRet = pcap_sendpacket(edrvInstance_l.pPcap, pBuffer_p->pBuffer,
                              (int)pBuffer_p->txFrameSize);
    if (pcapRet != 0)
    {
        DEBUG_LVL_EDRV_TRACE("%s() pcap_sendpacket returned %d (%s)\n",
                             __func__, pcapRet, pcap_geterr(edrvInstance_l.pPcap));
        return kErrorInvalidOperation;
    }

    return kErrorOk;
}
开发者ID:Kalycito-open-automation,项目名称:openPOWERLINK_V2,代码行数:37,代码来源:edrv-pcap_win.c


示例7: output_inject_process

static int output_inject_process(void *obj, struct packet *p, struct proto_process_stack *s, unsigned int stack_index) {

	struct output_inject_priv *priv = obj;

	struct proto_process_stack *stack = &s[stack_index];

 	size_t len = stack->plen;
	if (len > 1500)
		len = 1500;

	int bytes = pcap_inject(priv->p, stack->pload, len);

	if (bytes == -1) {
		pomlog(POMLOG_ERR "Error while injecting packet : %s", pcap_geterr(priv->p));
		return POM_ERR;
	}

	registry_perf_inc(priv->perf_pkts_out, 1);
	registry_perf_inc(priv->perf_bytes_out, stack->plen);


	return POM_OK;

}
开发者ID:gmsoft-tuxicoman,项目名称:pom-ng,代码行数:24,代码来源:output_inject.c


示例8: main

int  main(int argc, char const *argv[])
{
	char ebuf[PCAP_ERRBUF_SIZE];
	pcap_t *pd;
	if (argc<=1){
		printf("usage :%s <network interface>\n", argv[0]);
		return 0;
	}

	if ((pd=pcap_open_live(argv[1],DEFAULT_SNAPLEN,1,1000,ebuf))==NULL)
	{
		(void)fprintf(stderr, "1:%s\n", ebuf);
	}

	if (pcap_loop(pd,-1,packet_print,NULL)<0)
	{
		(void)fprintf(stderr, "2:pcap_loop: %s\n", pcap_geterr(pd));
	}

	pcap_close(pd);


	return 0;
}
开发者ID:0xcc,项目名称:libpcap-tcp,代码行数:24,代码来源:eth_txt.c


示例9: bpf_compile

static PyObject*
bpf_compile(PyObject* self, PyObject* args)
{
  int linktype;
  int  snaplen;
  char *filter;
  int optimize;
  unsigned int netmask;

  if(!PyArg_ParseTuple(args,
		       "iispI:compile",
		       &linktype,
		       &snaplen,
		       &filter,
		       &optimize,
		       &netmask))
    return NULL;

  pcap_t *pp;

  pp = pcap_open_dead(linktype, snaplen);
  if(pp == NULL)
    return NULL;

  struct bpf_program bpf;
  int status = pcap_compile(pp, &bpf, filter, optimize, netmask);
  pcap_close(pp);

  if(status)
    {
      PyErr_SetString(PcapError, pcap_geterr(pp));
      return NULL;
    }

  return new_bpfobject( &bpf );
}
开发者ID:neirbowj,项目名称:pcapy,代码行数:36,代码来源:pcapy.c


示例10: pcaprr_daq_acquire

static int pcaprr_daq_acquire(
    void *handle, int cnt, DAQ_Analysis_Func_t callback, void *user)
{
    Pcaprr_Context_t *context = (Pcaprr_Context_t *) handle;
    int ret, i;
    pcap_t *thandle;

    context->analysis_func = callback;
    context->user_data = user;

    context->packets = 0;
    while (context->packets < cnt || cnt <= 0)
    {
	for (i = 0 ; i < context->handle_count ; i++) {
		thandle = context->handle[i];

	        ret = pcap_dispatch(
        	    thandle, cnt-context->packets, pcap_process_loop, (void *) context);

/* fprintf(stderr, "dispatch %d %d %d\n", i, cnt, ret); */
	        if (ret == -1)
	        {
	            DPE(context->errbuf, "%s", pcap_geterr(thandle));
	            return ret;
	        }
	        /* In read-file mode, PCAP returns 0 when it hits the end of the file. */
	        else if (context->file && ret == 0)
	            return DAQ_READFILE_EOF;
	        /* If we hit a breakloop call or timed out without reading any packets, break out. */
	        else if (ret == -2 || ret == 0)
	            break;
	    }
    }

    return 0;
}
开发者ID:jeffmurphy,项目名称:DAQ-PCAPRR,代码行数:36,代码来源:daq_pcaprr.c


示例11: print_stats

/* Print packet capture statistics */
void print_stats() {
        struct pcap_stat pkt_stats;
        float run_time;

        if (pcap_hnd && !use_infile) {
                if (pcap_stats(pcap_hnd, &pkt_stats) != 0) {
                        WARN("Cannot obtain packet capture statistics: %s", pcap_geterr(pcap_hnd));
                        return;
                }

                LOG_PRINT("%d packets received, %d packets dropped, %d http packets parsed", \
                     pkt_stats.ps_recv, pkt_stats.ps_drop, num_parsed);

                run_time = (float) (time(0) - start_time);
                if (run_time > 0) {
                        LOG_PRINT("%0.1f packets/min, %0.1f http packets/min", \
                             ((pkt_stats.ps_recv * 60) / run_time), ((num_parsed * 60) / run_time));
                }
        } else if (pcap_hnd) {
                PRINT("%d http packets parsed", num_parsed);
        }

        return;
}
开发者ID:wishdev,项目名称:httpry,代码行数:25,代码来源:httpry.c


示例12: RETURN_CODE

	int	PcapWrapper::sendPacket(int adapter_id, unsigned char* packet_buffer, int buffer_size) {
	#ifdef WIN32
		if (!checkForAdapterId(adapter_id)) {
			// specified adapter not found
			RETURN_CODE(RC(ADAPTER_NOT_FOUND));
		}
		pcap_t*	handle = NULL;
		if (static_cast<int>(m_adapter_handles.size()) > adapter_id) {
			handle = m_adapter_handles[adapter_id];
		}
		if (!handle) {
			fprintf(stderr, "Error: retrievePacket() called on unopened adapter.\n");
			RETURN_CODE(RC(ACCESS_ON_UNOPENED_HANDLE));
		}
		if (pcap_sendpacket(handle, packet_buffer, buffer_size ) < 0) {
			fprintf(stderr, "Error: Failed to send the given packet: \n", pcap_geterr(handle));
			RETURN_CODE(RC(UNSPECIFIED_ERROR_OCCURED));
		}
		RETURN_CODE(RC(NORMAL_EXECUTION));
	#else
		fprintf(stderr, "Error: Wrong function called. pcap_sendpacket(...) only works with WinPcap.\n");
		RETURN_CODE(RC(UNSPECIFIED_ERROR_OCCURED));
	#endif
	}
开发者ID:Ryan--Yang,项目名称:whisper-library,代码行数:24,代码来源:pcapwrapper.cpp


示例13: main


//.........这里部分代码省略.........
      if ( ip_init(&ip_config, IP_SET_MEMCPY) )
      {
        printf("[!] Unable to initialise the IP library.\n");
        exit_clean(1);
      }
      else
        printf("[*] IP library using \"memcpy\" set.\n");
   }
   else if ( (mode & MODE_DEV) && dev) {
      if (getuid()) {
         printf("[*] You must be root..\n");
         exit_clean(1);
      }

      printf("[*] Running cxtracker %s\n",VERSION);

      //errbuf[0] = '\0';
      /* look up an availible device if non specified */
      if (dev == 0x0) dev = pcap_lookupdev(errbuf);
      printf("[*] Device: %s\n", dev);

      if ((handle = pcap_open_live(dev, SNAPLENGTH, 1, 500, errbuf)) == NULL) {
         printf("[*] Error pcap_open_live: %s \n", errbuf);
         exit_clean(1);
      }

      // in pcap_open_live(), libpcap maintains a heap allocated buffer
      // for reading off the wire. we can use pointer copies here for 
      // improved speed
      if ( ip_init(&ip_config, IP_SET_MEMCPY) )
      {
        printf("[*] Unable to initialise the IP library.\n");
        exit_clean(1);
      }
      else
        printf("[*] IP library using \"memcpy\" set.\n");

      if ( chroot_flag == 1 ) {
         set_chroot();
      }

      if(daemon_flag) {
         if(!is_valid_path(pidpath))
            printf("[*] PID path \"%s\" is bad, check privilege.",pidpath);
            openlog("cxtracker", LOG_PID | LOG_CONS, LOG_DAEMON);
            printf("[*] Daemonizing...\n\n");
            go_daemon();
      }
   }
   else
   {
      printf("[*] You must specify where to read from.\n");
      exit_clean(1);
   }

   if ((pcap_compile(handle, &cfilter, bpff, 1 ,net_mask)) == -1) {
      printf("[*] Error pcap_compile user_filter: %s\n", pcap_geterr(handle));
      exit_clean(1);
   }

   if (pcap_setfilter(handle, &cfilter)) {
      printf("[*] Unable to set pcap filter!  (%s)\n", pcap_geterr(handle));
   } else {
      pcap_freecode(&cfilter); // filter code not needed after setfilter
   }

   // set up dump mode now as appropriate
   if (mode & MODE_DUMP ) {
      printf("[*] Writing traffic to %s%s.*, rolling every %d %s\n",
          dpath, dump_file_prefix, (int)roll_point, rollover_names[(int)roll_type]);
      dump_file_open();
   }

   /* B0rk if we see an error... */
   if (strlen(errbuf) > 0) {
      printf("[*] Error errbuf: %s \n", errbuf);
      exit_clean(1);
   }

   if(drop_privs_flag) {
      printf("[*] Dropping privs...\n\n");
      drop_privs();
   }

   bucket_keys_NULL();

   alarm(TIMEOUT);
   if (read_file) {
      printf("[*] Reading packets...\n");
   } else {
      printf("[*] Sniffing...\n");
   }

   roll_time_last = time(NULL);
   pcap_loop(handle,-1,got_packet,NULL);

   game_over();

   return 0;
}
开发者ID:jandre,项目名称:cxtracker,代码行数:101,代码来源:cxtracker.c


示例14: rtp_collect

void* rtp_collect( void* device ) {

        struct bpf_program filter;
        char errbuf[PCAP_ERRBUF_SIZE];
        char *filter_expr;
        uint16_t snaplen = 65535, timeout = 100, len = 300, ret = 0;        

        if(device) {
            if((sniffer_rtp = pcap_open_live((char *)device, snaplen, rtcp_promisc, timeout, errbuf)) == NULL) {
                LERR("Failed to open packet sniffer on %s: pcap_open_live(): %s\n", (char *)device, errbuf);
                return NULL;
            }
        } else  {
            if((sniffer_rtp = pcap_open_offline(usefile, errbuf)) == NULL) {
                LERR("Failed to open packet sniffer rtp on %s: pcap_open_offline(): %s\n", usefile, errbuf);
                return NULL;
            }
        }

        len += (rtcp_portrange != NULL) ? strlen(rtcp_portrange) : 10;        
        len += (rtcp_userfilter != NULL) ? strlen(rtcp_userfilter) : 0;        
        filter_expr = malloc(sizeof(char) * len);
        
        ret += snprintf(filter_expr, len, RTCP_FILTER);
                        
        /* FILTER */
        if(rtcp_portrange != NULL) ret += snprintf(filter_expr+ret, (len - ret), "%s portrange %s ", ret ? " and": "", rtcp_portrange);

        /* CUSTOM FILTER */
        if(rtcp_userfilter != NULL) ret += snprintf(filter_expr+ret, (len - ret), " %s", rtcp_userfilter);

        /* compile filter expression (global constant, see above) */
        if (pcap_compile(sniffer_rtp, &filter, filter_expr, 1, 0) == -1) {
                LERR("Failed to compile filter \"%s\": %s\n", filter_expr, pcap_geterr(sniffer_rtp));
                if(filter_expr) free(filter_expr);
                return NULL;
        }

        /* install filter on sniffer session */
        if (pcap_setfilter(sniffer_rtp, &filter)) {
                LERR("Failed to install filter: %s\n", pcap_geterr(sniffer_rtp));
                if(filter_expr) free(filter_expr);
                return NULL;
        }

        if(filter_expr) free(filter_expr);
        
        /* detect link_offset. Thanks ngrep for this. */
        switch(pcap_datalink(sniffer_rtp)) {
                case DLT_EN10MB:
                    link_offset = ETHHDR_SIZE;
                    break;

                case DLT_IEEE802:
                    link_offset = TOKENRING_SIZE;
                    break;

                case DLT_FDDI:
                    link_offset = FDDIHDR_SIZE;
                    break;

                case DLT_SLIP:
                    link_offset = SLIPHDR_SIZE;
                    break;

                case DLT_PPP:
                    link_offset = PPPHDR_SIZE;
                    break;

                case DLT_LOOP:
                case DLT_NULL:
                    link_offset = LOOPHDR_SIZE;
                    break;

                case DLT_RAW:
                    link_offset = RAWHDR_SIZE;
                    break;

                case DLT_LINUX_SLL:
                    link_offset = ISDNHDR_SIZE;
                    break;

                case DLT_IEEE802_11:
                    link_offset = IEEE80211HDR_SIZE;
                    break;

                default:
                    LERR( "fatal: unsupported interface type %u\n", pcap_datalink(sniffer_rtp));
                    exit(-1);
        }

        while (pcap_loop(sniffer_rtp, 0, (pcap_handler)rtcpback_proto, 0));


        /* terminate from here */
        handler(1);

        return NULL;
}
开发者ID:elementalvoid,项目名称:captagent,代码行数:99,代码来源:proto_rtcp.c


示例15: ReceivePcapThreadInit

/**
 * \brief Init function for ReceivePcap.
 *
 * This is a setup function for recieving packets
 * via libpcap. There are two versions of this function
 * depending on the major version of libpcap used.
 * For versions prior to 1.x we use open_pcap_live,
 * for versions 1.x and greater we use pcap_create + pcap_activate.
 *
 * \param tv pointer to ThreadVars
 * \param initdata pointer to the interface passed from the user
 * \param data pointer gets populated with PcapThreadVars
 *
 * \todo Create a general pcap setup function.
 */
TmEcode ReceivePcapThreadInit(ThreadVars *tv, const void *initdata, void **data)
{
    SCEnter();
    PcapIfaceConfig *pcapconfig = (PcapIfaceConfig *)initdata;

    if (initdata == NULL) {
        SCLogError(SC_ERR_INVALID_ARGUMENT, "initdata == NULL");
        SCReturnInt(TM_ECODE_FAILED);
    }

    PcapThreadVars *ptv = SCMalloc(sizeof(PcapThreadVars));
    if (unlikely(ptv == NULL)) {
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }
    memset(ptv, 0, sizeof(PcapThreadVars));

    ptv->tv = tv;

    ptv->livedev = LiveGetDevice(pcapconfig->iface);
    if (ptv->livedev == NULL) {
        SCLogError(SC_ERR_INVALID_VALUE, "Unable to find Live device");
        SCFree(ptv);
        SCReturnInt(TM_ECODE_FAILED);
    }

    SCLogInfo("using interface %s", (char *)pcapconfig->iface);

    if (LiveGetOffload() == 0) {
        (void)GetIfaceOffloading((char *)pcapconfig->iface, 1, 1);
    } else {
        DisableIfaceOffloading(ptv->livedev, 1, 1);
    }

    ptv->checksum_mode = pcapconfig->checksum_mode;
    if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) {
        SCLogInfo("Running in 'auto' checksum mode. Detection of interface state will require "
                  xstr(CHECKSUM_SAMPLE_COUNT) " packets.");
    }

    /* XXX create a general pcap setup function */
    char errbuf[PCAP_ERRBUF_SIZE];
    ptv->pcap_handle = pcap_create((char *)pcapconfig->iface, errbuf);
    if (ptv->pcap_handle == NULL) {
        if (strlen(errbuf)) {
            SCLogError(SC_ERR_PCAP_CREATE, "Couldn't create a new pcap handler for %s, error %s",
                    (char *)pcapconfig->iface, errbuf);
        } else {
            SCLogError(SC_ERR_PCAP_CREATE, "Couldn't create a new pcap handler for %s",
                    (char *)pcapconfig->iface);
        }
        SCFree(ptv);
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }

    if (pcapconfig->snaplen == 0) {
        /* We set snaplen if we can get the MTU */
        ptv->pcap_snaplen = GetIfaceMaxPacketSize(pcapconfig->iface);
    } else {
        ptv->pcap_snaplen = pcapconfig->snaplen;
    }
    if (ptv->pcap_snaplen > 0) {
        /* set Snaplen. Must be called before pcap_activate */
        int pcap_set_snaplen_r = pcap_set_snaplen(ptv->pcap_handle, ptv->pcap_snaplen);
        if (pcap_set_snaplen_r != 0) {
            SCLogError(SC_ERR_PCAP_SET_SNAPLEN, "Couldn't set snaplen, error: %s", pcap_geterr(ptv->pcap_handle));
            SCFree(ptv);
            pcapconfig->DerefFunc(pcapconfig);
            SCReturnInt(TM_ECODE_FAILED);
        }
        SCLogInfo("Set snaplen to %d for '%s'", ptv->pcap_snaplen,
                  pcapconfig->iface);
    }

    /* set Promisc, and Timeout. Must be called before pcap_activate */
    int pcap_set_promisc_r = pcap_set_promisc(ptv->pcap_handle, pcapconfig->promisc);
    //printf("ReceivePcapThreadInit: pcap_set_promisc(%p) returned %" PRId32 "\n", ptv->pcap_handle, pcap_set_promisc_r);
    if (pcap_set_promisc_r != 0) {
        SCLogError(SC_ERR_PCAP_SET_PROMISC, "Couldn't set promisc mode, error %s", pcap_geterr(ptv->pcap_handle));
        SCFree(ptv);
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }

//.........这里部分代码省略.........
开发者ID:norg,项目名称:suricata,代码行数:101,代码来源:source-pcap.c


示例16: capture_init


//.........这里部分代码省略.........
                   PCAP_TIMEOUT, pcap_errbuf);
   
   ON_ERROR(pd, NULL, "pcap_open: %s", pcap_errbuf);

   /* 
    * update to the reap assigned snapshot.
    * this may be different reading from files
    */
   DEBUG_MSG("requested snapshot: %d assigned: %d", GBL_PCAP->snaplen, pcap_snapshot(pd));
   GBL_PCAP->snaplen = pcap_snapshot(pd);
  
   /* get the file size */
   if (GBL_OPTIONS->read) {
      struct stat st;
      fstat(fileno(pcap_file(pd)), &st);
      GBL_PCAP->dump_size = st.st_size;
   }

   /* set the pcap filters */
   if (GBL_PCAP->filter != NULL && strcmp(GBL_PCAP->filter, "")) {

      DEBUG_MSG("pcap_filter: %s", GBL_PCAP->filter);
   
      if (pcap_lookupnet(GBL_OPTIONS->iface, &net, &mask, pcap_errbuf) == -1)
         ERROR_MSG("%s", pcap_errbuf);

      if (pcap_compile(pd, &bpf, GBL_PCAP->filter, 1, mask) < 0)
         ERROR_MSG("%s", pcap_errbuf);
            
      if (pcap_setfilter(pd, &bpf) == -1)
         ERROR_MSG("pcap_setfilter");

      pcap_freecode(&bpf);
   }
   
   /* if in bridged sniffing, we have to open even the other iface */
   if (GBL_SNIFF->type == SM_BRIDGED) {
      pb = pcap_open_live(GBL_OPTIONS->iface_bridge, GBL_PCAP->snaplen, GBL_PCAP->promisc, 
                   PCAP_TIMEOUT, pcap_errbuf);
   
      ON_ERROR(pb, NULL, "%s", pcap_errbuf);
   
      /* set the pcap filters */
      if (GBL_PCAP->filter != NULL) {
   
         if (pcap_lookupnet(GBL_OPTIONS->iface_bridge, &net, &mask, pcap_errbuf) == -1)
            ERROR_MSG("%s", pcap_errbuf);

         if (pcap_compile(pb, &bpf, GBL_PCAP->filter, 1, mask) < 0)
            ERROR_MSG("%s", pcap_errbuf);
            
         if (pcap_setfilter(pb, &bpf) == -1)
            ERROR_MSG("pcap_setfilter");

         pcap_freecode(&bpf);
      }
   }


   /* open the dump file */
   if (GBL_OPTIONS->write) {
      DEBUG_MSG("pcapfile_out: %s", GBL_OPTIONS->pcapfile_out);
      pdump = pcap_dump_open(pd, GBL_OPTIONS->pcapfile_out);
      ON_ERROR(pdump, NULL, "%s", pcap_geterr(pd));
      GBL_PCAP->dump = pdump;               
   }
   
   /* set the right dlt type for the iface */
   GBL_PCAP->dlt = pcap_datalink(pd);
     
   DEBUG_MSG("capture_init: %s [%d]", pcap_datalink_val_to_description(GBL_PCAP->dlt), GBL_PCAP->dlt);
   USER_MSG("(%s)\n\n", pcap_datalink_val_to_description(GBL_PCAP->dlt));
 
   /* check that the bridge type is the same as the main iface */
   if (GBL_SNIFF->type == SM_BRIDGED && pcap_datalink(pb) != GBL_PCAP->dlt)
      FATAL_ERROR("You can NOT bridge two different type of interfaces !");
   
   /* check if we support this media */
   if (get_decoder(LINK_LAYER, GBL_PCAP->dlt) == NULL) {
      if (GBL_OPTIONS->read)
         FATAL_ERROR("Dump file not supported (%s)", pcap_datalink_val_to_description(GBL_PCAP->dlt));
      else
         FATAL_ERROR("Inteface \"%s\" not supported (%s)", GBL_OPTIONS->iface, pcap_datalink_val_to_description(GBL_PCAP->dlt));
   }
   
   /* set the alignment for the buffer */
   set_alignment(GBL_PCAP->dlt);
   
   /* allocate the buffer for the packets (UINT16_MAX) */
   SAFE_CALLOC(GBL_PCAP->buffer, UINT16_MAX + GBL_PCAP->align, sizeof(char));
  
   /* set the global descriptor for both the iface and the bridge */
   GBL_PCAP->pcap = pd;               
   if (GBL_SNIFF->type == SM_BRIDGED)
      GBL_PCAP->pcap_bridge = pb;
 
   /* on exit clean up the structures */
   atexit(capture_close);
   
}
开发者ID:ASSmodeus,项目名称:dsploit,代码行数:101,代码来源:ec_capture.c


示例17: main

int
main(int argc, char **argv)
{
	register int op;
	register char *cp, *cmdbuf, *device;
	long longarg;
	char *p;
	int timeout = 1000;
	int immediate = 0;
	int nonblock = 0;
	bpf_u_int32 localnet, netmask;
	struct bpf_program fcode;
	char ebuf[PCAP_ERRBUF_SIZE];
	int status;
	int packet_count;

	device = NULL;
	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	opterr = 0;
	while ((op = getopt(argc, argv, "i:mnt:")) != -1) {
		switch (op) {

		case 'i':
			device = optarg;
			break;

		case 'm':
			immediate = 1;
			break;

		case 'n':
			nonblock = 1;
			break;

		case 't':
			longarg = strtol(optarg, &p, 10);
			if (p == optarg || *p != '\0') {
				error("Timeout value \"%s\" is not a number",
				    optarg);
				/* NOTREACHED */
			}
			if (longarg < 0) {
				error("Timeout value %ld is negative", longarg);
				/* NOTREACHED */
			}
			if (longarg > INT_MAX) {
				error("Timeout value %ld is too large (> %d)",
				    longarg, INT_MAX);
				/* NOTREACHED */
			}
			timeout = (int)longarg;
			break;

		default:
			usage();
			/* NOTREACHED */
		}
	}

	if (device == NULL) {
		device = pcap_lookupdev(ebuf);
		if (device == NULL)
			error("%s", ebuf);
	}
	*ebuf = '\0';
	pd = pcap_create(device, ebuf);
	if (pd == NULL)
		error("%s", ebuf);
	status = pcap_set_snaplen(pd, 65535);
	if (status != 0)
		error("%s: pcap_set_snaplen failed: %s",
			    device, pcap_statustostr(status));
	if (immediate) {
		status = pcap_set_immediate_mode(pd, 1);
		if (status != 0)
			error("%s: pcap_set_immediate_mode failed: %s",
			    device, pcap_statustostr(status));
	}
	status = pcap_set_timeout(pd, timeout);
	if (status != 0)
		error("%s: pcap_set_timeout failed: %s",
		    device, pcap_statustostr(status));
	status = pcap_activate(pd);
	if (status < 0) {
		/*
		 * pcap_activate() failed.
		 */
		error("%s: %s\n(%s)", device,
		    pcap_statustostr(status), pcap_geterr(pd));
	} else if (status > 0) {
		/*
		 * pcap_activate() succeeded, but it's warning us
		 * of a problem it had.
		 */
		warning("%s: %s\n(%s)", device,
		    pcap_statustostr(status), pcap_geterr(pd));
//.........这里部分代码省略.........
开发者ID:hemengsi123,项目名称:libpcap,代码行数:101,代码来源:capturetest.c


示例18: main

int main(){
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i = 0;
	pcap_t *adhandle;
	int res;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct tm *ltime;
	char timestr[16];
	struct pcap_pkthdr *header;
	const u_char *pkt_data;
	time_t local_tv_sec;


	/* 获取本机设备列表 */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &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", &inum);

	if (inum < 1 || inum > i)
	{
		printf("\nInterface number out of range.\n");
		/* 释放设备列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* 跳转到已选中的适配器 */
	for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);

	/* 打开设备 */
	if ((adhandle = pcap_open(d->name,          // 设备名
		65536,            // 要捕捉的数据包的部分 
		// 65535保证能捕获到不同数据链路层上的每个数据包的全部内容
		PCAP_OPENFLAG_PROMISCUOUS,    // 混杂模式
		1000,             // 读取超时时间
		NULL,             // 远程机器验证
		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);

	/* 释放设备列表 */
	pcap_freealldevs(alldevs);

	/* 获取数据包 */
	while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0){

		if (res == 0)
			/* 超时时间到 */
			continue;

		/* 将时间戳转换成可识别的格式 */
		local_tv_sec = header->ts.tv_sec;
		ltime = localtime(&local_tv_sec);
		strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);

		printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
	}

	if (res == -1){
		printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
		return -1;
	}

	return 0;
}
开发者ID:narata,项目名称:C-program,代码行数:95,代码来源:源1.cpp


示例19: main

int main(int argc, char **argv)
{
	int c, n, i, proto, packet_size, pause_us, retransmit, file_size, num_packets, npacket;
	char *end;
	libnet_t *ln_ctx;
	char ln_errbuf[LIBNET_ERRBUF_SIZE];
	struct libnet_ether_addr *ln_hwaddr;
	libnet_ptag_t ln_ptag;
	pcap_t *pcap_ctx;
	char pcap_errbuf[PCAP_ERRBUF_SIZE], pcap_fp_str[64];
	struct bpf_program pcap_fp;
	struct pcap_pkthdr pcap_hdr;
	FILE *fp;
	unsigned char buf[ETH_DATA_LEN], dest_mac_addr[ETH_ALEN];
	struct pkt_hdr *pkt_hdr;
	struct vlan_eth_hdr *vlan_eth_hdr;

	proto = 0xCAFE;
	packet_size = ETH_DATA_LEN - PKT_HDR_SIZE;
	pause_us = 1000;
	retransmit = 3;

	while ((c = getopt(argc, argv, "p:s:w:r:")) != -1)
	{
		switch (c)
		{
			case 'p':
				proto = strtol(optarg, &end, 0);
				if ((*end != '\0'))
					usage(argv[0]);
			break;

			case 's':
				packet_size = strtol(optarg, &end, 0);
				if ((*end != '\0'))
					usage(argv[0]);

				if ((packet_size <= 0) || (packet_size > (ETH_DATA_LEN - PKT_HDR_SIZE)))
					packet_size = ETH_DATA_LEN - PKT_HDR_SIZE;
			break;

			case 'w':
				pause_us = strtol(optarg, &end, 0);
				if ((*end != '\0'))
					usage(argv[0]);

				if (pause_us <= 0)
					pause_us = 1;
			break;

			case 'r':
				retransmit = strtol(optarg, &end, 0);
				if ((*end != '\0'))
					usage(argv[0]);

				if (retransmit < 0)
					retransmit = 0;
			break;

			case '?':
			default:
				fprintf(stderr, "unrecognized option: %c\n", c);
				usage(argv[0]);
		}
	}

	if (argc != (optind + 3))
		usage(argv[0]);

	if (strlen(argv[optind]) <= 0)
		usage(argv[0]);

	ln_ctx = libnet_init(LIBNET_LINK, argv[optind], ln_errbuf);
	if (ln_ctx == NULL)
	{
		fprintf(stderr, "couldn't initialize libnet context: %s\n", ln_errbuf);
		exit(1);
	}

	if (str2mac(argv[optind + 1], dest_mac_addr) != 0)
		usage(argv[0]);

	pcap_ctx = pcap_open_live(argv[optind], BUFSIZ, 1, 1000, pcap_errbuf);
	if (pcap_ctx == NULL)
	{
		fprintf(stderr, "couldn't initialize pcap context: %s\n", pcap_errbuf);
		exit(1);
	}

	sprintf(pcap_fp_str, "ether proto 0x%04x and ether src %02x:%02x:%02x:%02x:%02x:%02x",
		proto, dest_mac_addr[0], dest_mac_addr[1], dest_mac_addr[2], dest_mac_addr[3],
		dest_mac_addr[4], dest_mac_addr[5]);

	printf("pcap filter: %s\n", pcap_fp_str);

	if (pcap_compile(pcap_ctx, &pcap_fp, pcap_fp_str, 0, PCAP_NETMASK_UNKNOWN) == -1)
	{
		fprintf(stderr, "couldn't compile pcap filter: %s\n", pcap_geterr(pcap_ctx));
		exit(1);
	}
//.........这里部分代码省略.........
开发者ID:Alexandersss,项目名称:COBRA-7-3,代码行数:101,代码来源:sendfile.c


示例20: main

int main(int argc, char** argv) {
	int c, index;
	char *interface = NULL;
	char *file = NULL;
	char *strng = 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:s:")) {
		switch (c) {
			case 'h' :
				print_usage();
				return;
			case 'i' :
				interface = optarg;
				break;
			case 'r' :
				file = optarg;
				break;
			case 's' :
				strng = 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) {
//		printf("Offline Case\n");
		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 {
//			printf("Default interface needs to be used\n");
			interface = pcap_lookupdev(errbuf);
			if (!interface) {
				fprintf(stderr, "Couldn't find default device : %s\n", errbuf);
				return (2);
			}
//			printf("default interface : %s\n", interface);
		}
	}

	if (interface) {
		handle = pcap_open_live(interface, BUFSIZ, 1, 1000, 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);
		}
	}
	if (strng)
		pcap_loop(handle, 1000, got_packet, (u_char*)strng);
	else
//.........这里部分代码省略.........

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ pcap_inject函数代码示例发布时间:2022-05-30
下一篇:
C++ pcap_get_selectable_fd函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap