本文整理汇总了C++中pcap_compile函数的典型用法代码示例。如果您正苦于以下问题:C++ pcap_compile函数的具体用法?C++ pcap_compile怎么用?C++ pcap_compile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pcap_compile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
//.........这里部分代码省略.........
*/
cmdbuf = "";
}
}
if (useactivate) {
pd = pcap_create(device, ebuf);
if (pd == NULL)
error("%s: pcap_create() failed: %s", device, ebuf);
status = pcap_set_snaplen(pd, 65535);
if (status != 0)
error("%s: pcap_set_snaplen failed: %s",
device, pcap_statustostr(status));
status = pcap_set_promisc(pd, 1);
if (status != 0)
error("%s: pcap_set_promisc failed: %s",
device, pcap_statustostr(status));
if (dorfmon) {
status = pcap_set_rfmon(pd, 1);
if (status != 0)
error("%s: pcap_set_rfmon failed: %s",
device, pcap_statustostr(status));
}
status = pcap_set_timeout(pd, 1000);
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));
}
} else {
*ebuf = '\0';
pd = pcap_open_live(device, 65535, 1, 1000, ebuf);
if (pd == NULL)
error("%s", ebuf);
else if (*ebuf)
warning("%s", ebuf);
}
pcap_fd = pcap_fileno(pd);
/*
* Try setting a filter with an uninitialized bpf_program
* structure. This should cause valgrind to report a
* problem.
*
* We don't check for errors, because it could get an
* error due to a bad pointer or count.
*/
#if defined(USE_BPF)
ioctl(pcap_fd, BIOCSETF, &bad_fcode);
#elif defined(USE_SOCKET_FILTERS)
setsockopt(pcap_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bad_fcode,
sizeof(bad_fcode));
#endif
/*
* Try setting a filter with an initialized bpf_program
* structure that points to an uninitialized program.
* That should also cause valgrind to report a problem.
*
* We don't check for errors, because it could get an
* error due to a bad pointer or count.
*/
#if defined(USE_BPF)
bad_fcode.bf_len = INSN_COUNT;
bad_fcode.bf_insns = uninitialized;
ioctl(pcap_fd, BIOCSETF, &bad_fcode);
#elif defined(USE_SOCKET_FILTERS)
bad_fcode.len = INSN_COUNT;
bad_fcode.filter = uninitialized;
setsockopt(pcap_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bad_fcode,
sizeof(bad_fcode));
#endif
/*
* Now compile a filter and set the filter with that.
* That should *not* cause valgrind to report a
* problem.
*/
if (pcap_compile(pd, &fcode, cmdbuf, 1, 0) < 0)
error("can't compile filter: %s", pcap_geterr(pd));
if (pcap_setfilter(pd, &fcode) < 0)
error("can't set filter: %s", pcap_geterr(pd));
pcap_close(pd);
exit(status < 0 ? 1 : 0);
}
示例2: main
//.........这里部分代码省略.........
/* The interface value won't be set if capture files were specified; else, there should have been an interface specified */
if(!get_iface() && source != PCAP_FILE)
{
usage(argv[0]);
goto end;
}
else if(get_iface())
{
/* Get the MAC address of the specified interface */
read_iface_mac();
}
if(get_iface() && source == PCAP_FILE)
{
cprintf(CRITICAL, "[X] ERROR: -i and -f options cannot be used together.\n");
usage(argv[0]);
goto end;
}
/* If we're reading from a file, be sure we don't try to transmit probe requests */
if(source == PCAP_FILE)
{
passive = 1;
}
/* Open the output file, if any. If none, write to stdout. */
if(out_file)
{
fp = fopen(out_file, "wb");
if(!fp)
{
cprintf(CRITICAL, "[X] ERROR: Failed to open '%s' for writing\n", out_file);
goto end;
}
set_log_file(fp);
}
/*
* Loop through all of the specified capture sources. If an interface was specified, this will only loop once and the
* call to monitor() will block indefinitely. If capture files were specified, this will loop through each file specified
* on the command line and monitor() will return after each file has been processed.
*/
for(i=argc-1; i>0; i--)
{
/* If the source is a pcap file, get the file name from the command line */
if(source == PCAP_FILE)
{
/* If we've gotten to the arguments, we're done */
if((argv[i][0] == '-') ||
(last_optarg && (memcmp(argv[i], last_optarg, strlen(last_optarg)) == 0))
)
{
break;
}
else
{
target = argv[i];
}
}
/* Else, use the specified interface name */
else
{
target = get_iface();
}
set_handle(capture_init(target));
if(!get_handle())
{
cprintf(CRITICAL, "[X] ERROR: Failed to open '%s' for capturing\n", get_iface());
goto end;
}
if(pcap_compile(get_handle(), &bpf, PACKET_FILTER, 0, 0) != 0)
{
cprintf(CRITICAL, "[X] ERROR: Failed to compile packet filter\n");
goto end;
}
if(pcap_setfilter(get_handle(), &bpf) != 0)
{
cprintf(CRITICAL, "[X] ERROR: Failed to set packet filter\n");
goto end;
}
/* Do it. */
monitor(bssid, passive, source, channel, mode);
printf("\n");
}
ret_val = EXIT_SUCCESS;
end:
globule_deinit();
sql_cleanup();
if(bssid) free(bssid);
if(out_file) free(out_file);
if(wpsmon.fp) fclose(wpsmon.fp);
return ret_val;
}
示例3: capturePackets
/**
* capturePackets(void * arg) -> void *
*
* Captures the incoming packets and analyses the packets
**/
void * capturePackets(void * arg) {
pcap_t *pcapHandle;
char errorPcap[PCAP_ERRBUF_SIZE];
struct pcap_pkthdr *packHdr;
struct bpf_program filter;
char filter_exp[100] = "dst host ";
const u_char *packetData;
int readStatus, portNum;
bpf_u_int32 localIp;
//Convert local ip to 32 bit format
inet_pton(AF_INET, ps_args.localIP.c_str(), &localIp);
//Append the local machine ip to filter expression
strcat(filter_exp, ps_args.localIP.c_str());
//Open the specified interface for live capturing
pcapHandle = pcap_open_live("eth0", BUFSIZ, 0, 1000, errorPcap);
if(pcapHandle == NULL ){
fprintf(stderr,"Error in opening pcap for live capture: %s \n",errorPcap );
exit(EXIT_FAILURE);
}
//Add a filter to capture incoming packets only
if (pcap_compile(pcapHandle, &filter, filter_exp, 0, localIp) == -1) {
printf("Filter Parse Error %s: %s\n", filter_exp, pcap_geterr(pcapHandle));
exit(EXIT_FAILURE);
}
if (pcap_setfilter(pcapHandle, &filter) == -1) {
printf("Could not add filter %s: %s\n", filter_exp, pcap_geterr(pcapHandle));
exit(EXIT_FAILURE);
}
//Start sniffing the packets
while(1) {
//Check for pcap exit condition
pthread_mutex_lock(&pcapLock);
if(exitPcap == true) {
pthread_mutex_unlock(&pcapLock);
break;
}
pthread_mutex_unlock(&pcapLock);
//Capture the packet from Ethernet interface
readStatus = pcap_next_ex(pcapHandle, &packHdr, &packetData);
if(readStatus == -1) {
printf("Error reading packets: %s\n", pcap_geterr(pcapHandle));
}
if(readStatus > 0) {
struct iphdr *iph = (struct iphdr *)(packetData + ETH_HLEN);
//Get the destination port from the TCP Header
if(iph->protocol == IPPROTO_TCP) {
struct tcphdr *tcpH = (struct tcphdr *)(packetData + ETH_HLEN + iph->ihl* 4);
portNum = ntohs(tcpH->dest);
}
//Get the destination port from the UDP Header
else if (iph->protocol == IPPROTO_UDP) {
struct udphdr *udpH = (struct udphdr *)(packetData + ETH_HLEN + iph->ihl* 4);
portNum = ntohs(udpH->dest);
}
//Get the destination port from the ICMP Header
else if (iph->protocol == IPPROTO_UDP) {
struct icmphdr *icmpH = (struct icmphdr *) (packetData + ETH_HLEN + iph->ihl* 4);
portNum = getICMPPortNumber((u_char *)(packetData + ETH_HLEN + iph->ihl* 4 + sizeof(icmphdr)));
}
}
//Adds the packet to the global map
addToPacketList(portNum, (u_char *)packetData + ETH_HLEN);
}
//Close the pcap handle
pcap_close(pcapHandle);
pthread_exit(NULL);
}
示例4: main
//.........这里部分代码省略.........
if (opt_t38only){
ct->erase_non_t38=1;
}
signal(SIGINT,sigint_handler);
signal(SIGTERM,sigterm_handler);
if (ifname){
printf("Capturing on interface: %s\n", ifname);
/* Find the properties for interface */
if (pcap_lookupnet(ifname, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for interface %s: %s\n", ifname, errbuf);
net = 0;
mask = 0;
}
handle = pcap_open_live(ifname, 1600, opt_promisc, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open interface '%s': %s\n", ifname, errbuf);
return(2);
}
}else{
printf("Reading file: %s\n", fname);
net = 0;
mask = 0;
handle = pcap_open_offline(fname, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open pcap file '%s': %s\n", ifname, errbuf);
return(2);
}
}
chdir(opt_chdir);
/* 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);
}
if (opt_fork){
// daemonize
if (fork()) exit(0);
}
{
int dlt=pcap_datalink(handle);
switch (dlt){
case DLT_EN10MB :
offset_to_ip=sizeof(struct ether_header);
break;
case DLT_LINUX_SLL :
offset_to_ip=16;
break;
case DLT_RAW :
offset_to_ip=0;
break;
default : {
printf("Unknown interface type (%d).\n",dlt);
return 3;
}
}
}
示例5: init_socket
int init_socket(unsigned int loc_idx) {
struct bpf_program filter;
char errbuf[PCAP_ERRBUF_SIZE];
char filter_expr[FILTER_LEN];
int len=0, buffer_size = 0;
LDEBUG("Activating device: %s\n", profile_socket[loc_idx].device);
if (profile_socket[loc_idx].device) {
buffer_size = 1024 * 1024 * profile_socket[loc_idx].ring_buffer;
if ((sniffer_proto[loc_idx] = pcap_create((char *) profile_socket[loc_idx].device, errbuf)) == NULL) {
LERR("Failed to open packet sniffer on %s: pcap_create(): %s", (char * )profile_socket[loc_idx].device, errbuf);
return -1;
};
if (pcap_set_promisc(sniffer_proto[loc_idx], profile_socket[loc_idx].promisc) == -1) {
LERR("Failed to set promisc \"%s\": %s", (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx]));
return -1;
};
if (pcap_set_timeout(sniffer_proto[loc_idx], profile_socket[loc_idx].timeout) == -1) {
LERR("Failed to set timeout \"%s\": %s", (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx]));
return -1;
};
if (pcap_set_snaplen(sniffer_proto[loc_idx], profile_socket[loc_idx].snap_len) == -1) {
LERR("Failed to set snap_len [%d], \"%s\": %s", profile_socket[loc_idx].snap_len, (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx]));
return -1;
};
if (pcap_set_buffer_size(sniffer_proto[loc_idx], buffer_size) == -1) {
LERR("Failed to set buffer_size [%d] \"%s\": %s", buffer_size, (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx]));
return -1;
};
if (pcap_activate(sniffer_proto[loc_idx]) != 0) {
LERR("Failed to activate \"%s\": %s", (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx]));
return -1;
};
LDEBUG("Activated device: [%s]\n", profile_socket[loc_idx].device);
} else {
if ((sniffer_proto[loc_idx] = pcap_open_offline(usefile, errbuf)) == NULL) {
LERR("%s: Failed to open packet sniffer on %s: pcap_open_offline(): %s", module_name, usefile, errbuf);
return -1;
}
LNOTICE("Sending file: %s", usefile);
}
/* create filter string */
if(profile_socket[loc_idx].filter && strlen(profile_socket[loc_idx].filter) > 0)
{
len += snprintf(filter_expr+len, sizeof(filter_expr)-len, "(%s)", profile_socket[loc_idx].filter);
if(ipv4fragments || ipv6fragments)
{
if (ipv4fragments)
{
LDEBUG("Reassembling of IPv4 packets is enabled, adding '%s' to filter", BPF_DEFRAGMENTION_FILTER_IPV4);
len += snprintf(filter_expr+len, sizeof(filter_expr), " or %s", BPF_DEFRAGMENTION_FILTER_IPV4);
}
if (ipv6fragments)
{
LDEBUG("Reassembling of IPv6 packets is enabled, adding '%s' to filter", BPF_DEFRAGMENTION_FILTER_IPV6);
len += snprintf(filter_expr+len, sizeof(filter_expr), " or %s", BPF_DEFRAGMENTION_FILTER_IPV6);
}
}
}
if(profile_socket[loc_idx].capture_filter)
{
if(!strncmp(profile_socket[loc_idx].capture_filter, "rtcp", 4))
{
len += snprintf(filter_expr+len, sizeof(filter_expr), "%s %s", len ? " and" : "", RTCP_FILTER);
}
else if(!strncmp(profile_socket[loc_idx].capture_filter, "rtp", 3))
{
len += snprintf(filter_expr+len, sizeof(filter_expr), "%s %s", len ? " and" : "", RTP_FILTER);
}
}
LNOTICE("Using filter: %s", filter_expr);
/* compile filter expression (global constant, see above) */
if (pcap_compile(sniffer_proto[loc_idx], &filter, filter_expr, 1, 0) == -1) {
LERR("Failed to compile filter \"%s\": %s", filter_expr, pcap_geterr(sniffer_proto[loc_idx]));
return -1;
}
/* install filter on sniffer session */
if (pcap_setfilter(sniffer_proto[loc_idx], &filter)) {
LERR("Failed to install filter: %s", pcap_geterr(sniffer_proto[loc_idx]));
return -1;
}
//.........这里部分代码省略.........
示例6: strcpy
/**
* @brief 打开制定索引的设备
*
* @param int selIndex 传入需要打开设备的索引,索引号码从0开始
* @param int selFilter 传入包过滤器,默认值为-1,表示截取所有类型的包
*
* @return bool 返回true表示打开成功,返回false表示打开失败
*/
bool Wincap::OpenDevice(int selIndex, int selFilter/* = -1*/)
{
bool bRet = false;
u_int netmask;
struct bpf_program fcode;
do{
//判断所有索引是否符合,如果不符合则跳出
if ((selIndex < 0 || selIndex >= mDevCount) ||
(selFilter != -1 && (selFilter < 0 || selFilter >= mFilter.size())))
{
const char* errormsg = "打开索引错误,请确认后再尝试";
strcpy(mErrbuf, errormsg);
break;
}
pcap_if_t* seldev = nullptr;
pcap_if_t* dev = mAlldev;
//根据索引找到需要打开的设备
for (int i = 0; i < selIndex; i++)
{
dev = dev->next;
}
seldev = dev;
//打开需要打开的设备
if ((mAdhandle = pcap_open_live(seldev->name, 65536, 1, 1000, mErrbuf)) == nullptr)
{
const char* errormsg = "打开指定的设备出错,请确认后再尝试";
strcpy(mErrbuf, errormsg);
break;
}
//打开数据包连接
if (pcap_datalink(mAdhandle) != DLT_EN10MB)
{
const char* errormsg = "这不适合于非以太网的网络";
strcpy(mErrbuf, errormsg);
break;
}
//如果打开设备的地址存在,那么掩码否则传入默认值
if (dev->addresses != NULL)
netmask = ((struct sockaddr_in *)(dev->addresses->netmask))->sin_addr.S_un.S_addr;
else
netmask = 0xffffff;
//如果传入的过滤器是-1,那么表示所有类型的包都需要抓取
if (selFilter == -1)
{
char filter[] = "";
//将过滤器加载到已经打开设备,如果打开失败则跳出
if (pcap_compile(mAdhandle, &fcode, filter, 1, netmask) < 0)
{
const char* errormsg = "语法错误,无法编译过滤器";
strcpy(mErrbuf, errormsg);
break;
}
}
else
{
//保存选择的设备索引
std::string selfilter = mFilter[selFilter];
char* filter = new char[selfilter.length() + 1];
strcpy(filter, selfilter.c_str());
//将过滤器加载到已经打开的设备上面,如果打开失败则跳出
if (pcap_compile(mAdhandle, &fcode, filter, 1, netmask) < 0)
{
const char* errormsg = "语法错误,无法编译过滤器";
strcpy(mErrbuf, errormsg);
break;
}
}
//设置过滤器
if (pcap_setfilter(mAdhandle, &fcode) < 0)
{
const char* errormsg = "设置过滤器错误";
strcpy(mErrbuf, errormsg);
break;
}
//设置自动保存文件
if (mbSaveFile)
{
FileFind file;
char thistime[30];
struct tm* ltime;
//.........这里部分代码省略.........
示例7: main
int main(int argc, char** argv) {
char errbuf[PCAP_ERRBUF_SIZE];
char* interface = NULL;
char* outfile = NULL;
guint snaplen = 65536;
char* start_filter_str = NULL;
char* stop_filter_str = NULL;
char* capture_filter_str = NULL;
int promisc = 0;
int quiet = 0;
struct bpf_program start_filter;
struct bpf_program capture_filter;
pcap_t* capturer = NULL;
pcap_dumper_t* dumper = NULL;
int opt;
while ((opt = getopt(argc, argv, "i:w:s:b:e:f:phdq")) != -1) {
switch (opt) {
case 'i':
if (interface) panic(1,"interface already given");
interface = g_strdup(optarg);
break;
case 'w':
if (outfile) panic(3,"output file already given");
outfile = g_strdup(optarg);
break;
case 's':
snaplen = strtoul(optarg,NULL,10);
if ( snaplen == 0 )
panic(4,"invalid snaplen");
break;
case 'b':
if (start_filter_str) panic(5,"start filter already given");
start_filter_str = g_strdup(optarg);
break;
case 'e':
if (stop_filter_str) panic(6,"stop filter already given");
stop_filter_str = g_strdup(optarg);
break;
case 'f':
if (capture_filter_str) panic(7,"capture filter already given");
capture_filter_str = g_strdup(optarg);
break;
case 'p':
promisc = 1;
break;
case 'q':
quiet = 1;
break;
case 'd':
debug_level++;
break;
case 'h':
default:
usage(0);
break;
}
}
dprintf(1,"starting with:\n interface: %s\n snaplen: %d\n promisc: %d"
"\n outfile: %s\n capture filter: %s\n start: %s\n stop: %s\n debug level: %d\n",
interface ? interface : "to be chosen",
snaplen,
promisc,
outfile ? outfile : "** missing **",
capture_filter_str ? capture_filter_str : "** none given **",
start_filter_str ? start_filter_str : "** missing **",
stop_filter_str ? stop_filter_str : "** missing **",
debug_level);
if (! ( start_filter_str && stop_filter_str && outfile ) ) {
usage(10);
}
if (! interface) {
interface = pcap_lookupdev(errbuf);
if (!interface) {
panic(11, "could not obtain an interface: %s\n",errbuf);
}
}
#ifdef HAVE_PCAP_OPEN
if ( ! ( capturer = pcap_open(interface, snaplen, promisc, 1, NULL, errbuf) )) {
#else
if ( ! ( capturer = pcap_open_live(interface, snaplen, promisc, 1, errbuf) )) {
#endif
panic(12,"could not open interface '%s' for listener: %s\n",interface,errbuf);
}
dprintf(1,"opened listener (%s,%d,%d)\n",interface,snaplen, promisc);
if (pcap_compile(listener, &start_filter, start_filter_str, 1, 0) < 0) {
panic(13,"could not compile start filter: %s\n",pcap_geterr(listener));
}
dprintf(2,"compiled start filter %s\n",start_filter_str);
if (pcap_compile(listener, &stop_filter, stop_filter_str, 1, 0) < 0) {
panic(14,"could not compile stop filter: %s\n",pcap_geterr(listener));
}
//.........这里部分代码省略.........
示例8: main
int main(int argc, char **argv)
{
char *dev = NULL; /* capture device name */
char *filter_exp = "";
char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */
bpf_u_int32 mask; /* subnet mask */
bpf_u_int32 net; /* ip */
struct bpf_program fp; /* compiled filter program (expression) */
pcap_t *handle; /* packet capture handle */
int i; /* iterator for command-line argument */
int opt_flag = 0; /* option flag
1 for device
2 for filter
*/
/* check for capture device name on command-line */
if (argc >= 2) {
for( i = 1 ; i < argc ; i++) {
if (argv[i][0] == '-' || strlen(argv[i]) == 2) {
switch(argv[i][1]){
case 'D': /* device */
opt_flag = 1;
break;
case 'f': /* filter */
opt_flag = 2;
break;
default:
fprintf(stderr, "error option type %s\n", argv[i]);
exit(EXIT_FAILURE);
}
}
else if ( opt_flag == 0 ){/* expect -D -f */
fprintf(stderr, "Error for command-line: expect -D -f, but get %s\n", argv[i]);
exit(EXIT_FAILURE);
}
else{ /* expect argument */
switch( opt_flag ) {
case 1:
dev = argv[i];
break;
case 2:
filter_exp = argv[i];
break;
}
}
}
}
/* find a capture device if not specified on command-line */
if ( dev == NULL ){
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n",
errbuf);
exit(EXIT_FAILURE);
}
}
printf("Device: %s\n", dev);
printf("Filter expression: %s\n", filter_exp);
printf("DEBUG: opt_flag = %d\n", opt_flag);
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Can't get netmask for device %s\n", dev);
net = 0;
mask = 0;
}
printf("DEBUG: net = %d, mask = %d\n", net, mask);
/* 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);
}
printf("handle: %s\n", handle);
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);
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
printf("I am out.\n");
/* set callback function */
pcap_loop(handle, num_packets, get_packet, NULL);
/* cleanup */
//.........这里部分代码省略.........
示例9: wine_pcap_compile
int CDECL wine_pcap_compile(pcap_t *p, struct bpf_program *program, const char *buf, int optimize,
unsigned int mask)
{
TRACE("(%p %p %s %i %u)\n", p, program, debugstr_a(buf), optimize, mask);
return pcap_compile(p, program, buf, optimize, mask);
}
示例10: sniff
//.........这里部分代码省略.........
case PCAP_ERROR_NO_SUCH_DEVICE:
fprintf(stderr, "[Sniffer] ERROR: Device not found\n");
exit(1);
break;
case PCAP_ERROR_PERM_DENIED:
fprintf(stderr, "[Sniffer] ERROR: Permission denied\n");
exit(1);
break;
case PCAP_ERROR_PROMISC_PERM_DENIED:
fprintf(stderr, "[Sniffer] ERROR: Permission denied for promiscuous mode\n");
exit(1);
break;
case PCAP_ERROR_RFMON_NOTSUP:
fprintf(stderr, "[Sniffer] ERROR: Monitor mode is not supported\n");
exit(1);
break;
case PCAP_ERROR_IFACE_NOT_UP:
fprintf(stderr, "[Sniffer] ERROR: Interface %s is not available\n", (i == 0) ? device_in : device_out);
exit(1);
break;
default:
fprintf(stderr, "[Sniffer] ERROR: Unknown (%s)\n", pcap_geterr(hpcap[i]));
exit(1);
break;
}
}
if (i == 0) {
if (in_if) {
// Set capture direction (ingress only)
res = pcap_setdirection(hpcap[0], PCAP_D_IN);
if (res) {
fprintf(stderr, "[Sniffer] ERROR: Cannot set capture direction (pcap_setdirection error: %s, return value: %d)\n", pcap_geterr(hpcap[0]), res);
exit(1);
}
}
// Compile PCAP filter (IP packets)
res = pcap_compile(hpcap[0], &bpf, STR_FILTER, 0, PCAP_NETMASK_UNKNOWN);
if (res) {
fprintf(stderr, "[Sniffer] ERROR: Cannot compile packet filter (pcap_compile error: %s)\n", pcap_geterr(hpcap[0]));
exit(1);
}
res = pcap_setfilter(hpcap[0], &bpf);
if (res) {
fprintf(stderr, "[Sniffer] ERROR: Cannot set packet filter (pcap_setfilter error: %s, return value: %d)\n", pcap_geterr(hpcap[0]), res);
exit(1);
}
pcap_freecode(&bpf);
}
// Find data link type
if ((linktype[i] = pcap_datalink(hpcap[i])) < 0)
{
fprintf(stderr, "[Sniffer] Cannot determine data link type (pcap_datalink error: %s)\n", pcap_geterr(hpcap[i]));
exit(1);
}
if (i == 1 && linktype[0] != linktype[1]) {
fprintf(stderr, "[Sniffer] Incompatible link types (input=%d, output=%d)\n", linktype[0], linktype[1]);
exit(1);
}
}
linkHdrLen = 0;
switch (linktype[0])
{
case DLT_NULL:
linkHdrLen = 4;
break;
case DLT_EN10MB:
linkHdrLen = 14;
break;
case DLT_SLIP:
case DLT_PPP:
linkHdrLen = 24;
break;
default:
fprintf(stderr, "[Sniffer] Unsupported data link type: %d\n", linktype[0]);
exit(1);
}
// Prepare processor
processor = init_processor(machine, hpcap[0], hpcap[1], linkHdrLen, num_workers, no_report, batch);
_global_processor = processor;
// Set signal handler
signal(SIGINT, stop);
signal(SIGTERM, stop);
signal(SIGQUIT, stop);
// Run sniffer
gettimeofday(&(processor->start), NULL);
printf("[Sniffer] Sniffer is running (input: %s, outout: %s)...\n", in_if, out_if);
res = pcap_loop(hpcap[0], -1, process_packet, (unsigned char *)(processor));
stop(res);
}
示例11: getRemoteARP
int getRemoteARP(struct pm_cfg cfg, unsigned int targetIP, const char *device, char *mac)
{
unsigned int localIP;
char errbuf[PCAP_ERRBUF_SIZE] = {0};
ARPPACKET arp;
struct bpf_program fp;
struct pcap_pkthdr *header;
const u_char *pkt_data;
int sent = 0;
int found = 1;
char filter[100] = {0};
struct in_addr addr;
pcap_t *pHandle = pcap_open_live(device, SNAP_LEN, 0, ARP_WAIT_TIME, errbuf);
if (pHandle == NULL)
{
syslog(LOG_ERR, "unable to open capture device %s: %s", device, errbuf);
return -1;
}
if (getInterfaceIP(device, &localIP) < 0)
{
syslog(LOG_ERR, "unable to get IP address for %s", device);
pcap_close(pHandle);
return -1;
}
//send arp request to an IP.
memset(&arp, 0, sizeof(arp));
memset(arp.ethhdr.h_dest, 0xFF, ETH_ALEN);
arp.ethhdr.h_proto = htons(ETH_P_ARP);
arp.arphdr.ar_hrd = htons(ETH_P_802_3);
arp.arphdr.ar_pro = htons(ETH_P_IP);
arp.arphdr.ar_hln = ETH_ALEN; // Hardware size: 6(0x06)
arp.arphdr.ar_pln = 4; // Protocol size; 4
arp.arphdr.ar_op = htons(ARPOP_REQUEST); // Opcode: request (0x0001)
memset(arp.arphdr.ar_tha, 0, ETH_ALEN);
arp.arphdr.ar_tip = targetIP;
memcpy(arp.ethhdr.h_source, cfg.src_mac, ETH_ALEN);
memcpy(arp.arphdr.ar_sha, cfg.src_mac, ETH_ALEN);
arp.arphdr.ar_sip = localIP;
addr.s_addr = targetIP;
sprintf(filter, "arp host %s", inet_ntoa(addr));
pcap_compile(pHandle, &fp, filter, 0, 0);
pcap_setfilter(pHandle, &fp);
pcap_sendpacket(pHandle, (unsigned char *)&arp, sizeof(arp));
while (1) {
int res = pcap_next_ex(pHandle, &header, &pkt_data);
if (res == 1)
{
if (*(unsigned short *)(pkt_data + 12) == htons(0x0806) &&
header->len >= sizeof(ARPPACKET))
{
ARPPACKET* p = (ARPPACKET *)pkt_data;
if (p->arphdr.ar_op == htons(ARPOP_REPLY) && p->arphdr.ar_sip == targetIP)
{
memcpy(mac, (const char *)p->ethhdr.h_source, ETH_ALEN);
found = 0;
if (cfg.flags & PM_DEBUG)
{
syslog(LOG_INFO, "ARP reply on '%s'['%s'] filter '%s'",
device,
printMACStr(mac),
filter);
}
break;
}
}
}
if (res == 0)
{
if (sent++ < 2)
{
pcap_sendpacket(pHandle, (unsigned char *)&arp, sizeof(arp));
}
else
{
break;
}
}
if (res == -1)
{
syslog(LOG_ERR, "error reading packet: %s", pcap_geterr(pHandle));
break;
}
}
pcap_close(pHandle);
return found;
}
示例12: input_init
/* name : input_init
*/
static int input_init( probe_t *probe, int flags )
{
char *device = g_par.interface;
int dltype;
if ( flags & PROBE_OFFLINE ) {
/* open file */
if ( (probe->pcap=pcap_open_offline( device, errbuf )) ==NULL) {
errorf( "[%s] pcap_open_offline(): %s\n", device, errbuf );
return -1;
}
probe->cnt = 1;
}
else {
/* open interface */
int promisc = (flags&PROBE_PROMISC)?1:0;
char *p = probe->device;
if ( *device == '\0' ) {
if ((device=pcap_lookupdev( errbuf )) ==NULL) {
errorf( "pcap_lookupdev() failed: %s\n", errbuf );
return -1;
}
}
if ( (probe->pcap=pcap_open_live( device, g_snaplen, promisc,
100 /*ms*/, errbuf )) ==NULL ) {
/* todo!! */
errorf( "pcap_open_live(%s): %s\n", p, errbuf );
return -1;
}
probe->cnt = 1000;
}
switch ( dltype = pcap_datalink(probe->pcap) ) {
case DLT_EN10MB:
probe->dltype = dltype;
probe->offset = 14;
break;
case DLT_ATM_RFC1483:
probe->dltype = dltype;
probe->offset = 8;
break;
default:
probe->dltype = DLT_RAW;
probe->offset = 0;
}
if( g_par.filter != NULL ) {
if( (pcap_compile( probe->pcap, &probe->fprg, g_par.filter, 1, 0 ) <0)
|| (pcap_setfilter( probe->pcap, &probe->fprg ) <0) ) {
mlogf( 0, "[%s] unable to set filter: '%s'\n",
g_par.progname, g_par.filter );
} else {
mlogf( 1, "[%s] set filter to '%s'\n",
g_par.progname, g_par.filter );
}
}
mlogf( 1, "[%s] device: %s, dltype=%d, %s\n", g_par.progname,
(flags&PROBE_OFFLINE)?basename(device):device, probe->dltype,
(flags&PROBE_OFFLINE)?"offline"
:(flags&PROBE_PROMISC)?"promisc.":"no promisc." );
if ( flags & PROBE_OFFLINE ) {
probe->fd = fileno( pcap_file( probe->pcap ) );
probe->device = strdup( basename( device ) );
}
else {
probe->fd = pcap_fileno( probe->pcap );
probe->device = strdup( device );
}
if ( probe->fd >= 0) {
if ( mpoll_fdadd( probe->fd, MPOLL_IN,
cb_dispatch, (void*)probe ) <0 ) {
mlogf( 0, "[%s] %s\n", g_par.progname, strerror(errno) );
return -1;
}
mlogf( 2, "[%s] add fd %d to poll loop\n", g_par.progname, probe->fd );
}
if ( flow_init( &(probe->ipflows),
g_par.ipflow_max,
g_par.biflows,
g_par.ipflow_timeout ) <0 ) {
mlogf( 0, "[%s] ipflow initialisation failed: %s",
g_par.progname, strerror(errno) );
return -1;
}
return 0;
}
示例13: main
//.........这里部分代码省略.........
openlog(prog, 0, LOG_DAEMON);
if (chdir(arpdir) < 0) {
syslog(LOG_ERR, "chdir(%s): %m", arpdir);
syslog(LOG_ERR, "(using current working directory)");
}
if (rfilename != NULL) {
pd = pcap_open_offline(rfilename, errbuf);
if (pd == NULL) {
syslog(LOG_ERR, "pcap open %s: %s", rfilename, errbuf);
exit(1);
}
swapped = pcap_is_swapped(pd);
} else {
snaplen = max(sizeof(struct ether_header),
sizeof(struct fddi_header)) + sizeof(struct ether_arp);
timeout = 1000;
pd = pcap_open_live(interface, snaplen, 1, timeout, errbuf);
if (pd == NULL) {
syslog(LOG_ERR, "pcap open %s: %s", interface, errbuf);
exit(1);
}
#ifdef WORDS_BIGENDIAN
swapped = 1;
#endif
}
/*
* Revert to non-privileged user after opening sockets
* (not needed on most systems).
*/
setgid(getgid());
setuid(getuid());
/* Must be ethernet or fddi */
linktype = pcap_datalink(pd);
if (linktype != DLT_EN10MB && linktype != DLT_FDDI) {
syslog(LOG_ERR, "Link layer type %d not ethernet or fddi",
linktype);
exit(1);
}
/* Compile and install filter */
if (pcap_compile(pd, &code, "arp or rarp", 1, netmask) < 0) {
syslog(LOG_ERR, "pcap_compile: %s", pcap_geterr(pd));
exit(1);
}
if (pcap_setfilter(pd, &code) < 0) {
syslog(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pd));
exit(1);
}
if (rfilename == NULL)
syslog(LOG_INFO, "listening on %s", interface);
/* Read in database */
initializing = 1;
if (!readdata())
exit(1);
sorteinfo();
#ifdef DEBUG
if (debug > 2) {
debugdump();
exit(0);
}
#endif
initializing = 0;
(void)setsignal(SIGINT, die);
(void)setsignal(SIGTERM, die);
(void)setsignal(SIGHUP, die);
if (rfilename == NULL) {
(void)setsignal(SIGQUIT, checkpoint);
(void)setsignal(SIGALRM, checkpoint);
(void)alarm(CHECKPOINT);
}
switch (linktype) {
case DLT_EN10MB:
status = pcap_loop(pd, 0, process_ether, NULL);
break;
case DLT_FDDI:
status = pcap_loop(pd, 0, process_fddi, NULL);
break;
default:
syslog(LOG_ERR, "bad linktype %d (can't happen)", linktype);
exit(1);
}
if (status < 0) {
syslog(LOG_ERR, "pcap_loop: %s", pcap_geterr(pd));
exit(1);
}
pcap_close(pd);
if (!dump())
exit(1);
exit(0);
}
示例14: main
int main(int ac, char **av)
{
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
char filter_exp[FILTER_MAX_SIZE];
bpf_u_int32 mask;
bpf_u_int32 net;
u_char *packet;
pthread_t scheduler;
signal_prep();
packet=0;
e=init_env();
get_opt(ac, av);
#ifndef __APPLE__
if (!(e->option & OPT_VERBOSE))
daemon(ZERO,ZERO);
if (e->option & OPT_GARBAGE)
new_process(ac, av);
#endif
write_pid_number(e->pidfile_path);
if (IS_VERBOSE)
{
send_log(LOG_INFO, "[1] verbose : on\n");
send_log(LOG_DEBUG, "[2] Preallocate msg mem size (alignement not include) : %d x %u = %u\n",
e->max_tab_size,sizeof(t_msg),e->max_tab_size * (sizeof(t_msg)));
send_log(LOG_DEBUG, "[3] device : [%s]\n",e->dev);
send_log(LOG_DEBUG, "[4] filter : [%s]\n",e->filter);
}
if (pthread_mutex_init(&gl_lock_set_rmq, NULL) != 0)
{
send_log(LOG_CRIT, "[5] Mutex init failed\n");
mooner_exit(EXIT_MUTEX_ERR);
}
set_rmq_server_list();
if (pthread_mutex_init(&gl_lock_garbage, NULL) != 0)
{
send_log(LOG_CRIT, "[5] Mutex init failed\n");
mooner_exit(EXIT_MUTEX_ERR);
}
if (pthread_mutex_init(&gl_lock_send_data, NULL) != 0)
{
send_log(LOG_CRIT, "[44] Mutex init failed\n");
mooner_exit(EXIT_MUTEX_ERR);
}
if (pthread_create(&scheduler,NULL,th_scheduler,NULL) != ZERO)
{
send_log(LOG_CRIT, "[6] Can't create Thread for scheduling\n");
mooner_exit(EXIT_THREAD_CREA);
}
if (!IS_DEVICE)
e->dev = pcap_lookupdev(errbuf);
if (e->dev== NULL) {
send_log(LOG_ERR, "[7] Couldn't find default dev: %s\n", errbuf);
mooner_exit(2);
}
if (pcap_lookupnet(e->dev, &net, &mask, errbuf) == -1) {
send_log(LOG_ERR, "[8] Couldn't get netmask for dev %s: %s\n", e->dev, errbuf);
net = 0;
mask = 0;
}
handle = pcap_open_live(e->dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
send_log(LOG_ERR, "[9] Couldn't open dev %s: %s\n", e->dev, errbuf);
mooner_exit(2);
}
if (pcap_compile(handle, &fp, e->filter, 0, net) == -1) {
send_log(LOG_ERR, "[10] Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
mooner_exit(2);
}
if (pcap_setfilter(handle, &fp) == -1) {
send_log(LOG_ERR, "[11] Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
mooner_exit(2);
}
#ifdef DMALLOC
dmalloc_debug_setup("debug=0x4f47d03,log=logfile");
#endif
while(!(EXITING))
{
if (IS_VERBOSE)
send_log(LOG_DEBUG, "[12] entering loop\n");
pcap_loop(handle, -1, handle_packet, packet);
}
pcap_close(handle);
mooner_exit(ZERO);
return(ZERO);
}
示例15: main
//.........这里部分代码省略.........
infile = optarg;
break;
case 'O':
Oflag = 0;
break;
case 'm': {
bpf_u_int32 addr;
switch (inet_pton(AF_INET, optarg, &addr)) {
case 0:
error("invalid netmask %s", optarg);
break;
case -1:
error("invalid netmask %s: %s", optarg,
pcap_strerror(errno));
break;
case 1:
netmask = addr;
break;
}
break;
}
case 's': {
char *end;
snaplen = strtol(optarg, &end, 0);
if (optarg == end || *end != '\0'
|| snaplen < 0 || snaplen > 65535)
error("invalid snaplen %s", optarg);
else if (snaplen == 0)
snaplen = 65535;
break;
}
default:
usage();
/* NOTREACHED */
}
}
if (optind >= argc) {
usage();
/* NOTREACHED */
}
dlt = pcap_datalink_name_to_val(argv[optind]);
if (dlt < 0) {
dlt = (int)strtol(argv[optind], &p, 10);
if (p == argv[optind] || *p != '\0')
error("invalid data link type %s", argv[optind]);
}
if (infile)
cmdbuf = read_infile(infile);
else
cmdbuf = copy_argv(&argv[optind+1]);
#ifdef BDEBUG
pcap_set_optimizer_debug(dflag);
pcap_set_print_dot_graph(gflag);
#endif
pd = pcap_open_dead(dlt, snaplen);
if (pd == NULL)
error("Can't open fake pcap_t");
if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
error("%s", pcap_geterr(pd));
have_fcode = 1;
if (!bpf_validate(fcode.bf_insns, fcode.bf_len))
warn("Filter doesn't pass validation");
#ifdef BDEBUG
if (cmdbuf != NULL) {
// replace line feed with space
for (cp = cmdbuf; *cp != '\0'; ++cp) {
if (*cp == '\r' || *cp == '\n') {
*cp = ' ';
}
}
// only show machine code if BDEBUG defined, since dflag > 3
printf("machine codes for filter: %s\n", cmdbuf);
} else
printf("machine codes for empty filter:\n");
#endif
bpf_dump(&fcode, dflag);
free(cmdbuf);
if (have_fcode)
pcap_freecode (&fcode);
pcap_close(pd);
exit(0);
}