int main(int argc, char** argv) { int ret; int inum; int port; int i = 0; char err[PCAP_ERRBUF_SIZE]; char filter[32]; char loopback = 0; char *server = NULL; struct bpf_program fp; pcap_if_t *d; pcap_addr_t *a; signal(SIGINT, sig_handler); #ifndef _WIN32 ssl_InitSniffer(); #endif ssl_Trace("./tracefile.txt", err); if (pcap_findalldevs(&alldevs, err) == -1) err_sys("Error in pcap_findalldevs"); 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) err_sys("No interfaces found! Make sure pcap or WinPcap is installed"); printf("Enter the interface number (1-%d): ", i); scanf("%d", &inum); if (inum < 1 || inum > i) err_sys("Interface number out of range"); /* Jump to the selected adapter */ for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++); pcap = pcap_create(d->name, err); if (pcap == NULL) printf("pcap_create failed %s\n", err); if (d->flags & PCAP_IF_LOOPBACK) loopback = 1; /* get an IPv4 address */ for (a = d->addresses; a; a = a->next) { switch(a->addr->sa_family) { case AF_INET: server =iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr); printf("server = %s\n", server); break; } } if (server == NULL) err_sys("Unable to get device IPv4 address"); ret = pcap_set_snaplen(pcap, 65536); if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap)); ret = pcap_set_timeout(pcap, 1000); if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap)); ret = pcap_set_buffer_size(pcap, 1000000); if (ret != 0) printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap)); ret = pcap_set_promisc(pcap, 1); if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap)); ret = pcap_activate(pcap); if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap)); printf("Enter the port to scan: "); scanf("%d", &port); SNPRINTF(filter, sizeof(filter), "tcp and port %d", port); ret = pcap_compile(pcap, &fp, filter, 0, 0); if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap)); ret = pcap_setfilter(pcap, &fp); if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap)); ret = ssl_SetPrivateKey(server, port, "../../certs/server-key.pem", FILETYPE_PEM, NULL, err); if (ret != 0) err_sys(err); while (1) { struct pcap_pkthdr header; const unsigned char* packet = pcap_next(pcap, &header); if (packet) { byte data[65535]; if (header.caplen > 40) { /* min ip(20) + min tcp(20) */ int frame = ETHER_IF_FRAME_LEN; if (loopback) frame = LOCAL_IF_FRAME_LEN; packet += frame; header.caplen -= frame; } else continue; ret = ssl_DecodePacket(packet, header.caplen, data, err); if (ret < 0) printf("ssl_Decode ret = %d\n", ret); if (ret > 0) { data[ret] = 0; printf("SSL App Data:%s\n", data); } } } return 0; }
void packet_indexer(){ int i; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; const u_char *packet; struct pcap_pkthdr hdr; /* pcap.h */ long int indir_offset=0; char *token; int token_int; descr = pcap_open_offline("1.cap",errbuf); if(descr == NULL) { printf("pcap_open_offline(): %s\n",errbuf); exit(1); } const struct ip* iphdr; const struct sniff_tcp* tcp; const struct UDP_hdr *udp; FILE *indir,*sip[4],*dip[4],*port_f[2],*proto_f; //file openings indir=fopen("resources/Indirection.txt","w"); sip[0]=fopen("resources/Source1.txt","w"); sip[1]=fopen("resources/Source2.txt","w"); sip[2]=fopen("resources/Source3.txt","w"); sip[3]=fopen("resources/Source4.txt","w"); dip[0]=fopen("resources/Destination1.txt","w"); dip[1]=fopen("resources/Destination2.txt","w"); dip[2]=fopen("resources/Destination3.txt","w"); dip[3]=fopen("resources/Destination4.txt","w"); port_f[0]=fopen("resources/SourcePort.txt","w"); port_f[1]=fopen("resources/DestinPort.txt","w"); proto_f= fopen("resources/Protocol.txt","w"); //Generating Bitmap From Packets while(end_flag==0){ indir_offset=ftell(pcap_file(descr)); packet = pcap_next(descr,&hdr); if(packet != NULL){ fprintf(indir,"%ld\n",indir_offset); ++packet_count; /* jump past the ethernet header */ iphdr = (struct ip*)(packet + sizeof(struct ether_header)); /*printf("\nPacket Number:%d\n",packet_count); printf("Source:%s\n",inet_ntoa(iphdr->ip_src)); printf("Destination:%s\n",inet_ntoa(iphdr->ip_dst));*/ if(iphdr->ip_p==6){ //printf("Protocol:TCP\n"); tcp = (struct sniff_tcp*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); /*printf("Source Port:%d\n",ntohs(tcp->th_sport)); printf("Destination Port:%d\n",ntohs(tcp->th_dport));*/ port[0][packet_count-1][ntohs(tcp->th_sport)]=1; port[1][packet_count-1][ntohs(tcp->th_dport)]=1; proto[packet_count-1][0]=1; } else if(iphdr->ip_p==17){ //printf("Protocol:UDP\n"); udp=(struct UDP_hdr*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); /*printf("Source Port:%d\n",ntohs(udp->uh_sport)); printf("Destination Port:%d\n",ntohs(udp->uh_dport));*/ port[0][packet_count-1][ntohs(udp->uh_sport)]=1; port[1][packet_count-1][ntohs(udp->uh_dport)]=1; proto[packet_count-1][1]=1; } //Indirection Array //Source IP Tokenizing and normal bitmap index creation token = strtok(inet_ntoa(iphdr->ip_src), "."); i=0; while( token != NULL ){ token_int=atoi(token); src[i++][packet_count-1][token_int]=1; token = strtok(NULL, "."); } //Destination IP Tokenizing and normal bitmap index creation token = strtok(inet_ntoa(iphdr->ip_dst), "."); i=0; while( token != NULL ){ token_int=atoi(token); dst[i++][packet_count-1][token_int]=1; token = strtok(NULL, "."); } } else end_flag=1; }//end of while //Source Compression for(i=0;i<4;i++){ for(k=0;k<256;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(src[i][j][k]==0){ digit_type=0; digit_count=1; } else if(src[i][j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==src[i][j][k]){ digit_count++; } else { fprintf(sip[i],"%ld ",digit_count); fprintf(sip[i],"%ld ",digit_type); digit_type=src[i][j][k]; digit_count=1; } } }//j fprintf(sip[i],"%ld ",digit_count); fprintf(sip[i],"%ld ",digit_type); fprintf(sip[i],"\n"); }//k }//i //Destination comperssion for(i=0;i<4;i++){ for(k=0;k<256;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(dst[i][j][k]==0){ digit_type=0; digit_count=1; } else if(dst[i][j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==dst[i][j][k]){ digit_count++; } else { fprintf(dip[i],"%ld ",digit_count); fprintf(dip[i],"%ld ",digit_type); digit_type=dst[i][j][k]; digit_count=1; } } }//j fprintf(dip[i],"%ld ",digit_count); fprintf(dip[i],"%ld ",digit_type); fprintf(dip[i],"\n"); }//k }//i //Port comperssion for(i=0;i<2;i++){ for(k=0;k<65536;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(port[i][j][k]==0){ digit_type=0; digit_count=1; } else if(port[i][j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==port[i][j][k]){ digit_count++; } else { fprintf(port_f[i],"%ld ",digit_count); fprintf(port_f[i],"%ld ",digit_type); digit_type=port[i][j][k]; digit_count=1; } } }//j fprintf(port_f[i],"%ld ",digit_count); fprintf(port_f[i],"%ld ",digit_type); fprintf(port_f[i],"\n"); }//k }//i //End Port Compression //protocol compression for(k=0;k<2;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(proto[j][k]==0){ digit_type=0; digit_count=1; } else if(proto[j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==proto[j][k]){ digit_count++; } else { fprintf(proto_f,"%ld ",digit_count); fprintf(proto_f,"%ld ",digit_type); digit_type=proto[j][k]; digit_count=1; } } }//j fprintf(proto_f,"%ld ",digit_count); fprintf(proto_f,"%ld ",digit_type); fprintf(proto_f,"\n"); }//k fclose(indir); fclose(sip[0]); fclose(sip[1]); fclose(sip[2]); fclose(sip[3]); fclose(dip[0]); fclose(dip[1]); fclose(dip[2]); fclose(dip[3]); fclose(port_f[0]); fclose(port_f[1]); fclose(proto_f); pcap_close(descr); }
PyObject * captureObject_next(captureObject *self) { u_char *packet = NULL; struct pcap_pkthdr header; PyObject *ethernet = NULL; PyObject *result = NULL; PyObject *resultTuple = NULL; ethernet_t *eth_header = NULL; char buffer[255]; double packetTime; int packet_offset = 0; PyObject *remaining = NULL; int offset[5] = { 0, 0, 0, 0, 0 }; packet = (u_char *) pcap_next(self->pcap, &header); if (! packet) { Py_INCREF(Py_None); return Py_None; // PyErr_SetString(ErrorObject, "No data available before timeout"); // return NULL; } sprintf(buffer, "%ld.%ld", (long) header.ts.tv_sec, (long) header.ts.tv_usec); packetTime = strtod(buffer, NULL); result = PyList_New(0); switch (pcap_datalink(self->pcap)) { case DLT_EN10MB: { eth_header = (ethernet_t *) packet; ethernet = (PyObject *) PyProtocol_newEthernetObjectFromPacket(eth_header, &packet_offset); offset[0] = packet_offset; PyList_Append(result, ethernet); Py_DECREF(ethernet); switch (ntohs(eth_header->ether_type)) { case ETHERTYPE_IP: { if (! parseIP(result, header, packet, &packet_offset)) { Py_DECREF(result); return NULL; } offset[1] = packet_offset; break; } case ETHERTYPE_ARP: if (! parseARP(result, header, packet, &packet_offset)) { Py_DECREF(result); return NULL; } offset[2] = packet_offset; break; default: { } } break; } case DLT_NULL: { packet_offset = 4; if (! parseIP(result, header, packet, &packet_offset)) { Py_DECREF(result); return NULL; } offset[3] = packet_offset; break; } } if ((int) (header.len) - packet_offset < 0) { Py_DECREF(result); PyErr_Format(ErrorObject, "Parsed parsed end of packet (%d %d %d %d)", offset[0], offset[1], offset[2], offset[3]); return NULL; } remaining = PyString_FromStringAndSize((char *) (packet + packet_offset), header.len - packet_offset); PyList_Append(result, remaining); Py_DECREF(remaining); PyList_Append(result, PyFloat_FromDouble(packetTime)); resultTuple = PyList_AsTuple(result); Py_DECREF(result); return resultTuple; }
struct dns_packet * get_next_packet(struct dns_packet *decoded, pcap_parser_file * input) { /* Misc. variables */ char fqdn[MAX_NAME + 1]; unsigned int fqdn_length; /* pcap-related variables */ const uint8_t *packet; /* The actual packet */ struct pcap_pkthdr header; /* The header that pcap gives us */ const struct sniff_ethernet *ethernet; /* The ethernet header */ unsigned short ethertype; const struct sniff_ipv4 *ipv4; /* The IP header */ const struct sniff_ipv6 *ipv6; const struct sniff_udp *udp; /* The UDP header */ const struct sniff_dns *dns; u_int size_ip; u_int size_layer2; unsigned short ip_version; uint32_t family; const uint8_t *qsection; uint8_t labelsize; uint16_t add_type; uint16_t edns_size; uint16_t extended_rcode_and_version; uint16_t zpart; const uint8_t *sectionptr; const uint8_t *where_am_i; /* Cursor in packet */ bool end_of_name; unsigned int size_header; bool end_of_headers, fragmented; uint8_t next_v6_header; const struct sniff_eh *eh; /* The IPv6 extension header, if present */ const struct sniff_frag *frag; assert(decoded->qname != NULL); /* Grab next packet */ decoded->rank = input->packetnum; next_packet: packet = (uint8_t *) pcap_next(input->handle, &header); if (packet == NULL) { /* End of file */ return NULL; } input->packetnum++; decoded->length = header.len; decoded->captured_length = header.caplen; decoded->date = header.ts; if (input->firstpacket.tv_sec == 0 && input->firstpacket.tv_usec == 0) { input->firstpacket = header.ts; } input->lastpacket = header.ts; if (input->datalink == DLT_EN10MB) { size_layer2 = SIZE_ETHERNET; ethernet = (struct sniff_ethernet *) (packet); ethertype = ntohs(ethernet->ether_type); if (ethertype == VLAN_ETHERTYPE) { packet += 4; ethernet = (struct sniff_ethernet *) (packet); ethertype = ntohs(ethernet->ether_type); } if (ethertype == IPv6_ETHERTYPE) { ip_version = 6; } else if (ethertype == IPv4_ETHERTYPE) { ip_version = 4; } else { /* Ignore other Ethernet types */ goto next_packet; } } else if (input->datalink == DLT_LOOP) { size_layer2 = SIZE_LOOP; family = (ntohl(*((uint32_t *) packet))); if (family == PF_INET6) { ip_version = 6; } else if (family == PF_INET) { ip_version = 4; } else { /* Ignore other packet types */ goto next_packet; } } else { fatal("Unsupported data link type %s (%i)\n", pcap_datalink_val_to_description(input->datalink), input->datalink); } if (ip_version == 6) { ipv6 = (struct sniff_ipv6 *) (packet + size_layer2); size_ip = SIZE_IPv6; assert(IPV6_VERSION(ipv6) == 6); next_v6_header = ipv6->ip_nxt; size_header = 0; where_am_i = where_am_i + SIZE_IPv6; end_of_headers = false; fragmented = false; while (!end_of_headers) { /* Extension headers defined in RFC 2460, section 4 */ if (next_v6_header == 0 || next_v6_header == 43 || next_v6_header == 50 || next_v6_header == 51 || next_v6_header == 60) { eh = (struct sniff_eh *) (where_am_i); next_v6_header = eh->eh_next; size_header = eh->eh_length; } /* Fragment */ else if (next_v6_header == 44) { fragmented = 1; frag = (struct sniff_frag *) (where_am_i); next_v6_header = frag->frag_next; size_header = SIZE_FRAGMENT_HDR; } else { end_of_headers = true; } where_am_i = where_am_i + size_header; size_ip += size_header; if ((size_layer2 + size_ip) > decoded->captured_length) { if (verbose) { fprintf(stdout, "Warning: ignoring packet #%li because IPv6 headers too large\n", input->packetnum); } goto next_packet; } } if (fragmented && FRAG_OFFSET(frag) == 0) { goto next_packet; } } else if (ip_version == 4) { ipv4 = (struct sniff_ipv4 *) (packet + size_layer2); size_ip = IP_HL(ipv4) * 4; assert(IPV4_VERSION(ipv4) == 4); } else { /* Should never happen */ assert(0); } if ((ip_version == 6 && next_v6_header == UDP) || (ip_version == 4 && ipv4->ip_p == UDP)) { if (ip_version == 6) { assert(decoded->src != NULL); assert(decoded->dst != NULL); inet_ntop(AF_INET6, &ipv6->ip_src, decoded->src, INET6_ADDRSTRLEN); inet_ntop(AF_INET6, &ipv6->ip_dst, decoded->dst, INET6_ADDRSTRLEN); } else if (ip_version == 4) { assert(decoded->src != NULL); assert(decoded->dst != NULL); inet_ntop(AF_INET, &ipv4->ip_src, decoded->src, INET_ADDRSTRLEN); inet_ntop(AF_INET, &ipv4->ip_dst, decoded->dst, INET_ADDRSTRLEN); } else { goto next_packet; } udp = (struct sniff_udp *) (packet + size_layer2 + size_ip); decoded->src_port = (u_short) ntohs(udp->sport); decoded->dst_port = (u_short) ntohs(udp->dport); if (decoded->src_port == DNS_PORT || decoded->dst_port == DNS_PORT) { if (maxpackets > 0 && input->dnspacketnum >= maxpackets) { return NULL; } dns = (struct sniff_dns *) (packet + size_layer2 + size_ip + SIZE_UDP); decoded->query = DNS_QR(dns) == 0 ? true : false; decoded->query_id = dns->query_id; decoded->opcode = DNS_OPCODE(dns); decoded->returncode = DNS_RCODE(dns); decoded->aa = DNS_AA(dns) ? true : false; decoded->tc = DNS_TC(dns) ? true : false; decoded->rd = DNS_RD(dns) ? true : false; decoded->ra = DNS_RA(dns) ? true : false; decoded->ancount = ntohs(dns->ancount); decoded->nscount = ntohs(dns->nscount); decoded->arcount = ntohs(dns->arcount); qsection = (uint8_t *) (packet + size_layer2 + size_ip + SIZE_UDP + SIZE_DNS); fqdn[0] = '\0'; end_of_name = false; for (sectionptr = qsection; !end_of_name;) { CHECK_SECTIONPTR(1); labelsize = (uint8_t) * sectionptr; if (labelsize == 0) { sectionptr++; end_of_name = true; } else if (labelsize > 63) { /* It can be an error/attack or it can be compression (RFC 1035, * section 4.1.4). Today, we ignore packets with compression (we * just parse the question section, anyway). * * * * * * * * * TODO */ if (verbose) { fprintf(stdout, "Warning: ignoring packet #%li because labelsize > 63\n", input->packetnum); } goto next_packet; } else { CHECK_SECTIONPTR(labelsize); if (strlen(fqdn) == 0) { strncpy(fqdn, (char *) sectionptr + 1, labelsize); fqdn_length = labelsize; } else { fqdn_length = strlen(fqdn); if (fqdn_length + labelsize > MAX_NAME) { if (verbose) { fprintf(stdout, "Warning: ignoring packet #%li because malformed (FQDN length is already %i and label size is %i bytes)\n", input->packetnum, fqdn_length, labelsize); }; goto next_packet; } strncat(fqdn, ".", 1); strncat(fqdn, (char *) sectionptr + 1, labelsize); fqdn_length += (labelsize + 1); } if (fqdn_length > MAX_NAME) { if (verbose) { fprintf(stdout, "Warning: ignoring packet #%li because FQDN length > %i\n", input->packetnum, MAX_NAME); } goto next_packet; } fqdn[fqdn_length] = '\0'; sectionptr = sectionptr + labelsize + 1; CHECK_SECTIONPTR(0); } } CHECK_SECTIONPTR(2); strcpy(decoded->qname, fqdn); #ifdef PICKY_WITH_ALIGNMENT decoded->qtype = unaligned_uint16(sectionptr); #else decoded->qtype = ntohs(*((uint16_t *) sectionptr)); #endif sectionptr += 2; CHECK_SECTIONPTR(2); #ifdef PICKY_WITH_ALIGNMENT decoded->qclass = unaligned_uint16(sectionptr); #else decoded->qclass = ntohs(*((uint16_t *) sectionptr)); #endif sectionptr += 2; decoded->edns0 = false; if (decoded->query) { edns_size = 0; if (dns->ancount == 0 && dns->nscount == 0) { /* Probably by far the most common case in queries... */ if (dns->arcount != 0) { /* There is an additional section. * Probably the OPT * * * * * * * * * * * * * of EDNS */ CHECK_SECTIONPTR(1); labelsize = (uint8_t) * sectionptr; if (labelsize == 0) { /* Yes, EDNS0 */ sectionptr += 1; CHECK_SECTIONPTR(2); #ifdef PICKY_WITH_ALIGNMENT add_type = unaligned_uint16(sectionptr); #else add_type = ntohs(*((uint16_t *) sectionptr)); #endif sectionptr += 2; CHECK_SECTIONPTR(2); if (add_type == OPT) { #ifdef PICKY_WITH_ALIGNMENT edns_size = unaligned_uint16(sectionptr); #else edns_size = ntohs(*((uint16_t *) sectionptr)); #endif decoded->edns0 = true; /* RFC 2671 */ sectionptr += 2; CHECK_SECTIONPTR(2); #ifdef PICKY_WITH_ALIGNMENT extended_rcode_and_version = unaligned_uint16(sectionptr); #else extended_rcode_and_version = ntohs(*((uint16_t *) sectionptr)); #endif sectionptr += 2; CHECK_SECTIONPTR(2); #ifdef PICKY_WITH_ALIGNMENT zpart = unaligned_uint16(sectionptr); #else zpart = ntohs(*((uint16_t *) sectionptr)); #endif /* RFC 3225 */ decoded->do_dnssec = DNS_DO_DNSSEC(zpart) ? true : false; } sectionptr += 2; /* TODO: dissect the RDATA to find things like the option code (such as 3 for NSID) http://www.iana.org/assignments/dns-parameters */ } } } } if (decoded->edns0) { decoded->edns0_size = (unsigned int) edns_size; } input->dnspacketnum++; return decoded; } } goto next_packet; }
static void sniffer_callback (int unused, const short event, void * _interface) { interface_t * interface = _interface; pcap_t * pcap = interface -> pcap; struct pcap_pkthdr header; const unsigned char * packet; double delta; if (! interface -> maxcount || (interface -> partial + interface -> errors) < interface -> maxcount) { /* Please pcap give me next packet from the interface */ if ((packet = pcap_next (pcap, & header))) { interface -> partial ++; if (! (interface -> partial % hb)) { static unsigned long previous = 0; static struct timeval latest; struct timeval now; /* Show pkts/secs in the latest period */ gettimeofday (& now, NULL); delta = delta_time_in_milliseconds (& now, & latest); if (interface -> maxcount) printf ("%s: pkts rcvd #%lu of #%lu %s", progname, interface -> partial, interface -> maxcount, xpercentage (interface -> partial, interface -> maxcount)); else printf ("%s: pkts rcvd #%lu %s", progname, interface -> partial, xpercentage (interface -> partial, interface -> maxcount)); if (previous && delta) printf (" [%8.2f pkts/sec => +%lu pkts in %s]", (double) (interface -> partial - previous) * 1000 / delta, interface -> partial - previous, elapsed_time (& latest, & now)); printf ("\n"); previous = interface -> partial; latest = now; } } else interface -> errors ++; } else { gettimeofday (& interface -> stopped, NULL); delta = (double) delta_time_in_milliseconds (& interface -> stopped, & interface -> started); printf (" \n"); printf ("Time:\n"); printf ("=====\n"); print_time_in_secs (& interface -> started, "Started: "); print_time_in_secs (& interface -> stopped, "Finished: "); printf ("Elapsed Time: %s\n", elapsed_time (& interface -> started, & interface -> stopped)); printf ("\n"); /* Print out test results */ printf ("Great Totals:\n"); printf ("=============\n"); printf ("pkts rcvd #%lu pckts of #%lu => %7.2f pkts/sec\n\n", interface -> partial, interface -> maxcount, (double) interface -> partial * 1000 / delta); event_del (& interface -> read_evt); } }
int pcap_init(char *dev, uip_ipaddr_t* sip, uip_ipaddr_t* dip, struct uip_eth_addr* smac, struct uip_eth_addr* dmac, int special) { int i; int gotarp = 0; char error[PCAP_ERRBUF_SIZE]; const unsigned char* packet; struct pcap_pkthdr hdr; /* Open the output adapter */ if (NULL == (pcap_fp = pcap_open_live(dev, 1500, 1, PCAP_TIMEOUT_MS, error))) { fprintf(stderr,"Error opening adapter: %s\n", error); return -1; } while(!gotarp) { while (NULL == (packet = pcap_next(pcap_fp, &hdr))) { printf("No packet.\n"); } if (ETHERTYPE_ARP == myntohs(((struct ether_header *)packet)->ether_type)) { if (60 != hdr.len) { fprintf(stderr, "Expect arp with length 60, received %d\n", hdr.len); } else if (ARPOP_REQUEST != myntohs(((struct arphdr*)(packet + ETH_HLEN))->ar_op)) { fprintf(stderr, "Unexpected arp packet, opcode=%d\n", myntohs(((struct arphdr*)(packet + ETH_HLEN))->ar_op)); } else { gotarp = 1; } } else { fprintf(stderr, "Non arp received. Make sure, the device is connected directly!\n"); } } /* Grab MAC adress of router */ memmove(dmac, ((struct ether_header *)packet)->ether_shost, sizeof(*dmac)); /* Grab IP adress of router */ memmove(dip, packet + ETH_HLEN + sizeof(struct arphdr) + ETH_ALEN, 4); memmove(sip, packet + ETH_HLEN + sizeof(struct arphdr) + ETH_ALEN, 4); printf("Peer MAC: "); for (i = 0; i < (int)sizeof(*dmac); i++) { printf("%s%02x", 0 == i ? "" : ":", dmac->addr[i]); } printf("\n"); printf("Peer IP : %d.%d.%d.%d\n", P(*dip)[0], P(*dip)[1], P(*dip)[2], P(*dip)[3]); if (!special && 0 == P(*dip)[0] && 0 == P(*dip)[1] && 0 == P(*dip)[2] && 0 == P(*dip)[3]) { fprintf(stderr, "Telnet for RedBoot not enabled.\n"); return -1; } printf("Your MAC: "); for (i = 0; i < (int)sizeof(*smac); i++) { printf("%s%02x", 0 == i ? "" : ":", smac->addr[i]); } printf("\n"); P(*sip)[3] = 0 == P(*sip)[3] ? 1 : 0; printf("Your IP : %d.%d.%d.%d\n", P(*sip)[0], P(*sip)[1], P(*sip)[2], P(*sip)[3]); if (0 > pcap_setnonblock(pcap_fp, 1, error)) { fprintf(stderr,"Error setting non-blocking mode: %s\n", error); return -1; } return 0; }
/** * @brief Test the ROHC library with a flow of ROHC packets * * @param filename The name of the PCAP file that contains the ROHC packets * @param failure_start The first packet that shall fail to be decompressed * @return 0 in case of success, * 1 in case of failure */ static int test_decomp(const char *const filename, const size_t failure_start) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *handle; int link_layer_type; int link_len; struct pcap_pkthdr header; unsigned char *packet; struct rohc_decomp *decomp; unsigned int counter; int is_failure = 1; /* open the source dump file */ handle = pcap_open_offline(filename, errbuf); if(handle == NULL) { fprintf(stderr, "failed to open the source pcap file: %s\n", errbuf); goto error; } /* link layer in the source dump must be Ethernet */ link_layer_type = pcap_datalink(handle); if(link_layer_type != DLT_EN10MB && link_layer_type != DLT_LINUX_SLL && link_layer_type != DLT_RAW) { fprintf(stderr, "link layer type %d not supported in source dump (supported = " "%d, %d, %d)\n", link_layer_type, DLT_EN10MB, DLT_LINUX_SLL, DLT_RAW); goto close_input; } if(link_layer_type == DLT_EN10MB) { link_len = ETHER_HDR_LEN; } else if(link_layer_type == DLT_LINUX_SLL) { link_len = LINUX_COOKED_HDR_LEN; } else /* DLT_RAW */ { link_len = 0; } /* create the decompressor */ decomp = rohc_decomp_new2(ROHC_SMALL_CID, ROHC_SMALL_CID_MAX, ROHC_O_MODE); if(decomp == NULL) { fprintf(stderr, "cannot create the decompressor\n"); goto close_input; } /* set the callback for traces */ if(!rohc_decomp_set_traces_cb2(decomp, print_rohc_traces, NULL)) { fprintf(stderr, "failed to set trace callback\n"); goto destroy_decomp; } /* enable decompression profiles */ if(!rohc_decomp_enable_profiles(decomp, ROHC_PROFILE_UNCOMPRESSED, ROHC_PROFILE_UDP, ROHC_PROFILE_IP, ROHC_PROFILE_UDPLITE, ROHC_PROFILE_RTP, ROHC_PROFILE_ESP, ROHC_PROFILE_TCP, -1)) { fprintf(stderr, "failed to enable the decompression profiles\n"); goto destroy_decomp; } /* for each packet in the dump */ counter = 0; while((packet = (unsigned char *) pcap_next(handle, &header)) != NULL) { const struct rohc_ts arrival_time = { .sec = 0, .nsec = 0 }; struct rohc_buf rohc_packet = rohc_buf_init_full(packet, header.caplen, arrival_time); uint8_t ip_buffer[MAX_ROHC_SIZE]; struct rohc_buf ip_packet = rohc_buf_init_empty(ip_buffer, MAX_ROHC_SIZE); uint8_t rcvd_feedback_buf[6]; struct rohc_buf rcvd_feedback = rohc_buf_init_empty(rcvd_feedback_buf, 6); uint8_t send_feedback_buf[6]; struct rohc_buf send_feedback = rohc_buf_init_empty(send_feedback_buf, 6); rohc_status_t status; counter++; /* check Ethernet frame length */ if(header.len < link_len || header.len != header.caplen) { fprintf(stderr, "bad PCAP packet (len = %d, caplen = %d)\n", header.len, header.caplen); goto destroy_decomp; } /* skip the link layer header */ rohc_buf_pull(&rohc_packet, link_len); fprintf(stderr, "decompress malformed packet #%u:\n", counter); /* decompress the ROHC packet */ status = rohc_decompress3(decomp, rohc_packet, &ip_packet, &rcvd_feedback, &send_feedback); fprintf(stderr, "\tdecompression status: %s\n", rohc_strerror(status)); if(status == ROHC_STATUS_OK) { if(counter >= failure_start) { fprintf(stderr, "\tunexpected successful decompression\n"); goto destroy_decomp; } else { fprintf(stderr, "\texpected successful decompression\n"); } } else { if(counter >= failure_start) { fprintf(stderr, "\texpected decompression failure\n"); } else { fprintf(stderr, "\tunexpected decompression failure\n"); goto destroy_decomp; } } /* be ready to get the next feedback to send */ rohc_buf_reset(&send_feedback); } is_failure = 0; destroy_decomp: rohc_decomp_free(decomp); close_input: pcap_close(handle); error: return is_failure; } /** * @brief Callback to print traces of the ROHC library * * @param priv_ctxt An optional private context, may be NULL * @param level The priority level of the trace * @param entity The entity that emitted the trace among: * \li ROHC_TRACE_COMP * \li ROHC_TRACE_DECOMP * @param profile The ID of the ROHC compression/decompression profile * the trace is related to * @param format The format string of the trace */ static void print_rohc_traces(void *const priv_ctxt, const rohc_trace_level_t level, const rohc_trace_entity_t entity, const int profile, const char *const format, ...) { const char *level_descrs[] = { [ROHC_TRACE_DEBUG] = "DEBUG", [ROHC_TRACE_INFO] = "INFO", [ROHC_TRACE_WARNING] = "WARNING", [ROHC_TRACE_ERROR] = "ERROR" }; if(level >= ROHC_TRACE_WARNING || is_verbose) { va_list args; fprintf(stdout, "[%s] ", level_descrs[level]); va_start(args, format); vfprintf(stdout, format, args); va_end(args); } }
int main(int argc, char **argv) { char *dev; /* name of the device to use */ bpf_u_int32 netp; /* ip */ bpf_u_int32 maskp = PCAP_NETMASK_UNKNOWN; /* subnet mask */ pcap_t* descr; struct bpf_program fp; /* hold compiled program */ #if 0 const u_char *packet; struct pcap_pkthdr hdr; /* pcap.h */ #endif char *filter; int opt; int ret; /* return code */ char errbuf[PCAP_ERRBUF_SIZE]; char buffilter[2000]; dev = DefaultDev; filter = DefaultFilter; while ((opt = getopt(argc, argv, "ei:")) != -1) { switch(opt) { case 'i': dev = optarg; break; case 'e': ExitOnError = 1; break; } } if (optind < argc) { sprintf (buffilter,"(%s) and ",filter); while (optind < argc) { // additional option assume filter // printf ("add filter '%s'\n", argv[optind]); strcat (buffilter,argv[optind]); strcat (buffilter," "); optind++; } filter = buffilter; // printf ("new filter '%s'\n",filter); } /* ask pcap for the network address and mask of the device */ /* ret = pcap_lookupnet(dev,&netp,&maskp,errbuf); if (ret == -1) { printf("%s\n",errbuf); exit(1); } printf("lookup ok '%s'\n",dev); */ descr = pcap_open_live(dev,BUFSIZ,0,100 /* ms */,errbuf); if (descr == NULL) { printf("pcap_open_live(): %s\n",errbuf); exit(1); } printf("openlive ok '%s'\n",dev); /* ret = pcap_set_snaplen(descr,DefaultSize); if (ret != 0) { printf("pcap_set_snaplen(): %s\n",errbuf); exit(1); } printf("openlive+snap_len ok '%s'\n",dev); */ ret = pcap_compile(descr,&fp,filter,0,maskp); if (ret == -1) { printf("pcap_compile(): %s\n",errbuf); exit(1); } printf("compile ok '%s'\n",filter); ret = pcap_setfilter(descr,&fp); if (ret == -1) { printf("pcap_setfilter(): %s\n",errbuf); exit(1); } printf("setfilter ok '%s'\n",filter); pcap_loop(descr,-1,my_callback,NULL); printf("done\n"); #if 0 while (1) { packet = pcap_next(descr,&hdr); if (!packet) { usleep(100000); continue; } printf("+\n"); } #endif exit(0); }
/*-------------------------------------------------------------------*/ int main(int argc, char **argv) { unsigned int pkt_counter = 1; /* packet counter */ /* unsigned long byte_counter=0; */ /* total bytes seen in entire trace */ /* unsigned long cur_counter=0; */ /* counter for current 1-second interval */ /* unsigned long current_ts=0; */ /* current timestamp */ struct tcphdr *mytcp; struct udphdr *myudp; int fnum; /* temporary packet buffers */ struct pcap_pkthdr header; /* The header that pcap gives us */ const u_char *packet; /* The actual packet */ /* check command line arguments */ if (argc < 2) { fprintf(stderr, "Usage: %s [input pcaps]\n", argv[0]); exit(EXIT_FAILURE); } /* -------- Begin Main Packet Processing Loop ------------------- */ /* loop through each pcap file in command line args */ for (fnum = 1; fnum < argc; fnum++) { /* ------------------ */ /* open the pcap file */ pcap_t *handle; char errbuf[PCAP_ERRBUF_SIZE]; /* not sure what to do with this, oh well */ handle = pcap_open_offline(argv[fnum], errbuf); /* call pcap library function */ if (handle == NULL) { fprintf(stderr, "Couldn't open pcap file %s: %s\n", argv[fnum], errbuf); return (2); } /* ----------------- */ /* begin processing the packets in this particular file, one at a time */ while ((packet = pcap_next(handle, &header)) != NULL) { /* header contains information about the packet (e.g. timestamp) */ u_char *pkt_ptr = (u_char *) packet; /* cast a pointer to the packet data */ /* parse the first (ethernet) header, grabbing the type field */ int ether_type = ((int)(pkt_ptr[12]) << 8) | (int)pkt_ptr[13]; int ether_offset = 0; if (ether_type == ETHER_TYPE_IP) /* most common */ ether_offset = 14; else if (ether_type == ETHER_TYPE_8021Q) /* dot1q tag ? */ ether_offset = 18; else fprintf(stderr, "Unknown ethernet type, %04X, skipping...\n", ether_type); /* parse the IP header */ pkt_ptr += ether_offset; /* skip past the Ethernet II header */ struct ip *ip_hdr = (struct ip *)pkt_ptr; /* point to an IP header structure */ int packet_length = ntohs(ip_hdr->ip_len); if (ip_hdr->ip_p == IPPROTO_UDP) { myudp = (struct udphdr *)(pkt_ptr + sizeof(struct ip)); int size_payload = packet_length - (sizeof(struct iphdr) + sizeof(struct udphdr)); printf("%04d UDP %s -> ", pkt_counter, inet_ntoa(ip_hdr->ip_src)); printf("%s port %d -> %d", inet_ntoa(ip_hdr->ip_dst), ntohs(myudp->uh_sport), ntohs(myudp->uh_dport)); printf(" packet_length %d\n", size_payload); print_content((unsigned char *)pkt_ptr + sizeof(struct iphdr) + sizeof(struct udphdr), size_payload); printf("\n"); } if (ip_hdr->ip_p == IPPROTO_TCP) { mytcp = (struct tcphdr *)(pkt_ptr + sizeof(struct ip)); int tcp_offset = mytcp->th_off * 4; int size_payload = packet_length - (sizeof(struct iphdr) + tcp_offset); if (size_payload > 0) { printf("%04d TCP %s -> ", pkt_counter, inet_ntoa(ip_hdr->ip_src)); printf("%s port %d -> %d", inet_ntoa(ip_hdr->ip_dst), ntohs(mytcp->th_sport), ntohs(mytcp->th_dport)); unsigned char *dump = (unsigned char *)pkt_ptr + sizeof(struct iphdr) + tcp_offset; printf(" packet_length %d\n", size_payload); print_content(dump, size_payload); printf("\n"); } } /* check to see if the next second has started, for statistics purposes */ #if 0 if (current_ts == 0) { /* this takes care of the very first packet seen */ current_ts = header.ts.tv_sec; } else if (header.ts.tv_sec > current_ts) { printf("%ld KBps\n", cur_counter / 1000); cur_counter = 0; /* reset counters */ current_ts = header.ts.tv_sec; /* update time interval */ } cur_counter += packet_length; byte_counter += packet_length; /* byte counter update */ #endif pkt_counter++; /* increment number of packets seen */ } pcap_close(handle); /* close the pcap file */ } return 0; }
void __pcapnav_trace_find_end(pcapnav_t *pn) { off_t num_bytes; u_char *hdrpos; struct pcap_pkthdr hdr; off_t offset_orig, tmp_offset; if ((pn->start_time.tv_sec == 0) && (pn->start_time.tv_usec == 0)) __pcapnav_trace_find_start(pn); pn->end_offset = 0; memset(&pn->end_time, 0, sizeof(struct bpf_timeval)); /* We go back in the trace far enough to see MAX_CHAIN_LENGTH * consecutive packets, but still use only the (smaller) search_buf. * Once we've found a valid packet, we use pcap to iterate to * the last valid header. This'll involve disk I/O, but is a * safer method than jumping near the end of the trace were we * cannot scan enough packets to be really sure. */ /* Remember current position */ offset_orig = pcapnav_get_offset(pn); if (pn->trace.length < (int) MAX_PACKET_SIZE(pn) * MAX_CHAIN_LENGTH) num_bytes = pn->trace.length; else num_bytes = MAX_PACKET_SIZE(pn) * MAX_CHAIN_LENGTH; __pcapnav_buf_fill(pn->search_buf, pn->fp, -num_bytes, SEEK_END, pn->search_buf->size); if (__pcapnav_header_search(pn, &hdrpos, &hdr) != PCAPNAV_DEFINITELY) { D(("Header search failed\n")); goto cleanup_return; } tmp_offset = pn->search_buf->offset + (hdrpos - pn->search_buf->buf); D(("Definite header at offset %lu\n", (long unsigned) tmp_offset)); pcapnav_set_offset(pn, tmp_offset - sizeof(struct pcap_file_header)); pn->end_time = hdr.ts; pn->end_caplen = hdr.caplen; pn->end_offset = pcapnav_get_offset(pn); /* Select last packet so that the offset is pointing * AT the last packet, not to the offset following it! */ for ( ; ; ) { tmp_offset = pcapnav_get_offset(pn) + sizeof(struct pcap_file_header); if (!pcap_next(pn->pcap, &hdr)) break; pn->end_time = hdr.ts; pn->end_caplen = hdr.caplen; pn->end_offset = tmp_offset; } D(("Finished -- last valid packet is at %lu, at %u.%u, captured %u bytes.\n", (long unsigned) pn->end_offset, (unsigned) pn->end_time.tv_sec, (unsigned) pn->end_time.tv_usec, pn->end_caplen)); cleanup_return: /* Rewind to old position */ pcapnav_set_offset(pn, offset_orig); }
static void send_packets_from_pcap(int first) { int l2_len, ip_pack_len, p_valid_flag = 0; bool stop; pcap_t *pcap; unsigned char *pkt_data, *frame, *ip_data; struct pcap_pkthdr pkt_hdr; pcap = clt_settings.pcap; if (pcap == NULL || read_pcap_over) { return; } gettimeofday(&cur_time, NULL); stop = check_read_stop(); while (!stop) { pkt_data = (u_char *) pcap_next(pcap, &pkt_hdr); if (pkt_data != NULL) { if (pkt_hdr.caplen < pkt_hdr.len) { tc_log_info(LOG_WARN, 0, "truncated packets,drop"); } else { ip_data = get_ip_data(clt_settings.pcap, pkt_data, pkt_hdr.len, &l2_len); if (l2_len < ETHERNET_HDR_LEN) { tc_log_info(LOG_WARN, 0, "l2 len is %d", l2_len); continue; } last_pack_time = pkt_hdr.ts; if (ip_data != NULL) { clt_settings.pcap_time = last_pack_time.tv_sec * 1000 + last_pack_time.tv_usec / 1000; ip_pack_len = pkt_hdr.len - l2_len; tc_log_debug2(LOG_DEBUG, 0, "frame len:%d, ip len:%d", pkt_hdr.len, ip_pack_len); frame = ip_data - ETHERNET_HDR_LEN; dispose_packet(frame, ip_pack_len + ETHERNET_HDR_LEN, ip_pack_len, &p_valid_flag); if (p_valid_flag) { tc_log_debug0(LOG_DEBUG, 0, "valid flag for packet"); if (first) { first_pack_time = pkt_hdr.ts; first = 0; } else { adj_v_pack_diff = timeval_diff(&last_v_pack_time, &last_pack_time); } /* set last valid packet time in pcap file */ last_v_pack_time = last_pack_time; stop = check_read_stop(); } else { tc_log_debug0(LOG_DEBUG, 0, "invalid flag"); } } } } else { tc_log_info(LOG_WARN, 0, "stop, null from pcap_next"); stop = true; read_pcap_over = true; } } }
int main(int argc,char **argv) { char *in_dev,*out_dev, *netaddr, *mask; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *in_descr,*out_descr; struct bpf_program fp,fp2; /* hold compiled program */ bpf_u_int32 maskp; /* subnet mask */ bpf_u_int32 netp,netp2; /* ip */ u_char* args = NULL; struct in_addr addr1, addr2; pid_t pid; /* Options must be passed in as a string because I am lazy */ /* grab a device to peak into... dev = pcap_lookupdev(errbuf); if(dev == NULL) { printf("%s\n",errbuf); exit(1); } */ in_dev = "eth1"; out_dev = "eth0"; /* open device for reading. NOTE: defaulting to promiscuous mode*/ /* pcap_t *pcap_open_live * (char *device,int snaplen, int prmisc,int to_ms,char *ebuf) */ /* prmisc=0: non-promiscuous mode */ in_descr = pcap_open_live(in_dev,BUFSIZ,1,500,errbuf); if(in_descr == NULL ) { printf("pcap_open_live(): %s\n",errbuf); exit(1); } out_descr = pcap_open_live(out_dev,BUFSIZ,1,500,errbuf); if(out_descr == NULL ) { printf("pcap_open_live(): %s\n",errbuf); exit(1); } //if(pcap_compile(descr,&fp,"net 140.114.195.0 mask 255.255.255.0",0,netp) == -1) if(pcap_compile(out_descr,&fp,"dst host 140.114.195.31 and tcp",0,netp) == -1) { fprintf(stderr,"Error calling pcap_compile out\n"); exit(1); } if(pcap_compile(in_descr,&fp2,"src host 192.168.1.3 and tcp",0,netp2) == -1) { fprintf(stderr,"Error calling pcap_compile in\n"); exit(1); } /* set the compiled program as the filter */ if(pcap_setfilter(in_descr,&fp2) == -1) { fprintf(stderr,"Error setting filter in\n"); exit(1); } if(pcap_setfilter(out_descr,&fp) == -1) { fprintf(stderr,"Error setting filter out\n"); exit(1); } /* ... and loop */ //pid=fork(); //if(pid<0){ // printf("fork failed.\n"); // } // else if(pid==0){ //pcap_loop(in_descr,atoi(argv[1]),my_callback,args); // } // else{ // pcap_loop(out_descr,atoi(argv[1]),my_callback,args); //} u_char *in_Packet, *out_Packet; struct pcap_pkthdr *in_phdr,*out_phdr; struct pcap_pkthdr inthdr,outthdr; count =0; memset(memory,0,100); while (1) { in_Packet = (u_char*)pcap_next(in_descr, &inthdr); out_Packet = (u_char*)pcap_next(out_descr, &outthdr); if (in_Packet != NULL) { in_phdr=&inthdr; my_callback(args,in_phdr,in_Packet); } if (out_Packet != NULL) { out_phdr=&outthdr; my_callback(args,out_phdr,out_Packet); } } fprintf(stdout,"\nfinished\n"); return 0; }
int main(int argc, char **argv) { pcap_t *pcap; char errbuf[PCAP_ERRBUF_SIZE]; const u_char *pkt; struct pcap_pkthdr hdr; struct ether_header *eptr; struct ip *ip_hdr; struct tcphdr *tcp_hdr; unsigned long nbp,nbip,nbtcp; unsigned long long totalSize; flow * flowrec; int c,optpkt; struct timeval t0,t1; uint32_t last_expiration,current_ts; // Default Paramaters for the classification labeling=clusterport; SSL_labeling=SSL_clusterport; sslparsing=0; threshold=-255; action=ACTION_LABEL; memory=NOOPTMEM; pktlimit=model.nbpackets; optpkt=pktlimit; stats.nbstats=0; bzero(stats.timeidx,sizeof(stats.timeidx)); bzero(stats.creations,sizeof(stats.creations)); bzero(stats.deletions,sizeof(stats.deletions)); nbflows=0; last_expiration=0; // Parsing options while ((c = getopt (argc, argv, "m:hCDPLSt:p:")) != -1) switch (c) { case 'h': usage(argv); break; case 'P': action=ACTION_PARSE; break; case 'L': action=ACTION_LABEL; break; case 'D': labeling=dominant; SSL_labeling=dominant; break; case 'C': labeling=clusterport; SSL_labeling=SSL_clusterport; break; case 'm': if (atoi(optarg)>=0) { memory=atoi(optarg); break; } else { fprintf(stderr,"Invalid Memory option\n"); usage(argv); } break; case 'S': sslparsing=1; break; case 't': if (atoi(optarg)>0) { threshold=-atoi(optarg); break; } else { fprintf(stderr,"Invalid threshold value\n"); usage(argv); } case 'p': if (atoi(optarg)>0) { optpkt=atoi(optarg); break; } else { fprintf(stderr,"Invalid packet value\n"); usage(argv); } case '?': if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); usage(argv); default: usage(argv); } if (action==ACTION_PARSE) pktlimit=optpkt; if (optind>=argc) { fprintf(stderr,"No file specified\n"); usage(argv); } // Opening pcap file fprintf(stderr,"Opening file : %s\n",argv[optind]); if ((pcap = pcap_open_offline(argv[optind], errbuf)) == NULL) { fprintf(stderr,"Error opening pcap file : %s\n",errbuf); usage(argv); } init_hashes (); // Empty connection to start list first_flow=(flow*)malloc(sizeof(flow)); first_flow->src.s_addr=0; first_flow->dst.s_addr=0; first_flow->sport=0; first_flow->dport=0; active_flows=first_flow; // Parse packets one by one nbp=0;nbip=0;nbtcp=0; totalSize=0; gettimeofday (&t0,NULL); while (pkt = pcap_next( pcap, &hdr )) { nbp++; totalSize+=hdr.len; current_ts=hdr.ts.tv_sec; if (last_expiration==0) last_expiration=current_ts; if (current_ts-last_expiration>CLEAN_TIME) { if (memory>=OPT_GARBAGE) clean_flows(first_flow->next,current_ts); statistics(current_ts-last_expiration); last_expiration=current_ts; } if (nbp % PRINTPKT== 0) { fprintf(stderr, "Pkt : %lu",nbp); fprintf(stderr, "\r"); fflush(stderr); } eptr = (struct ether_header *) pkt; if (ntohs (eptr->ether_type) != ETHERTYPE_IP) { continue; } else { nbip++; ip_hdr=(struct ip *)(pkt+14); if (ip_hdr->ip_p==IPPROTO_TCP && ((ntohs (ip_hdr->ip_off) & IP_OFFMASK)==0)) { nbtcp++; count_flow(ip_hdr,hdr.caplen-14,hdr.ts.tv_sec); } } } if (memory>=OPT_GARBAGE) clean_flows(first_flow->next,current_ts); statistics(current_ts-last_expiration); last_expiration=current_ts; dump_flows(first_flow->next); statistics(1); gettimeofday (&t1,NULL); pcap_close(pcap); fprintf(stderr,"\n%lu Packets parsed in %.2fms\n(%lu non-ip / %lu non-tcp)\n" "TCP Connections with Syn: %lu\n" "Total Volume: %llu\n" "Duration: %lu\n", nbp, (float)((t1.tv_sec-t0.tv_sec)*1000000 + (t1.tv_usec-t0.tv_usec))/1000, nbp-nbip,nbp-nbtcp,flow_hash->total_insert,totalSize,stats.timeidx[stats.nbstats]); //dump_hashtab_stats(flow_hash); //print_statistics(); }
int main(int argc,char *argv[]){ int i=0; bpf_u_int32 netaddr=0,mask=0; // network addr and netmask struct bpf_program filter; // bpf prog filter char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *desc = NULL; struct pcap_pkthdr pkthdr; // header of captured packets const unsigned char *packet = NULL; arphdr_t *arpheader = NULL; memset(errbuf,0,PCAP_ERRBUF_SIZE); if(argc != 2){ fprintf(stderr,"usage : %s <iface>\n",argv[0]); exit(1); } if((desc = pcap_open_live(argv[1],MAXCAPT,0,512,errbuf)) == NULL){ fprintf(stderr,"err : %s\n",errbuf); exit(1); } if(pcap_compile(desc,&filter,"arp",1,mask) == -1){ // pcap filter fprintf(stderr,"err : %s\n",pcap_geterr(desc)); exit(1); } if(pcap_setfilter(desc,&filter) == -1){ fprintf(stderr,"err : %s\n",pcap_geterr(desc)); exit(1); } while(1){ if((packet = pcap_next(desc,&pkthdr)) == NULL){ sleep(2); continue; } arpheader = (struct arphdr *)(packet+14); // pointer to arp header printf("\n\npkt size : %db\n",pkthdr.len); printf("hw type : %s\n",(ntohs(arpheader->htype) == 1) ? "Ethernet" : "Unknown"); printf("proto type : %s\n",(ntohs(arpheader->ptype) == 0x0800) ? "IPv4" : "Unknown"); printf("oper : %s\n",(ntohs(arpheader->oper) == ARP_REQ) ? "ARP request" : "ARP reply"); if(ntohs(arpheader->htype) == 1 && ntohs(arpheader->ptype) == 0x0800){ printf("\t"); for(i=0;i<6;i++){ printf("%02X:",arpheader->sha[i]); } printf(" --> "); for(i=00;i<6;i++){ printf("%02X:",arpheader->tha[i]); } printf("\n\t"); for(i=0;i<4;i++){ printf("%d.",arpheader->spa[i]); } printf(" -- > "); for(i=0;i<4;i++){ printf("%d.",arpheader->tpa[i]); } printf("\n"); } } return 0; }
int main(int argc, char **argv) { int i; char *dev; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; const u_char *packet; struct pcap_pkthdr hdr; /* pcap.h */ struct ether_header *eptr; /* net/ethernet.h */ u_char *ptr; /* printing out hardware header info */ /* grab a device to peak into... */ dev = "wlan0"; // pcap_lookupdev(errbuf); if(dev == NULL) { printf("%s\n",errbuf); exit(1); } printf("DEV: %s\n",dev); /* open the device for sniffing. pcap_t *pcap_open_live(char *device,int snaplen, int prmisc,int to_ms, char *ebuf) snaplen - maximum size of packets to capture in bytes promisc - set card in promiscuous mode? to_ms - time to wait for packets in miliseconds before read times out errbuf - if something happens, place error string here Note if you change "prmisc" param to anything other than zero, you will get all packets your device sees, whether they are intendeed for you or not!! Be sure you know the rules of the network you are running on before you set your card in promiscuous mode!! */ descr = pcap_open_live(dev,BUFSIZ,0,-1,errbuf); if(descr == NULL) { printf("pcap_open_live(): %s\n",errbuf); exit(1); } /* grab a packet from descr (yay!) u_char *pcap_next(pcap_t *p,struct pcap_pkthdr *h) so just pass in the descriptor we got from our call to pcap_open_live and an allocated struct pcap_pkthdr */ sleep(5); packet = pcap_next(descr,&hdr); if(packet == NULL) {/* dinna work *sob* */ printf("Didn't grab packet\n"); exit(1); } /* struct pcap_pkthdr { struct timeval ts; time stamp bpf_u_int32 caplen; length of portion present bpf_u_int32; lebgth this packet (off wire) } */ printf("Grabbed packet of length %d\n",hdr.len); // printf("Recieved at ..... %s\n",ctime((const time_t*)&hdr.ts.tv_sec)); printf("Ethernet address length is %d\n",ETHER_HDR_LEN); // lets start with the ether header... eptr = (struct ether_header *) packet; // Do a couple of checks to see what packet type we have.. if (ntohs (eptr->ether_type) == ETHERTYPE_IP) { printf("Ethernet type hex:%x dec:%d is an IP packet\n", ntohs(eptr->ether_type), ntohs(eptr->ether_type)); }else if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) { printf("Ethernet type hex:%x dec:%d is an ARP packet\n", ntohs(eptr->ether_type), ntohs(eptr->ether_type)); }else { printf("Ethernet type %x not IP\n", ntohs(eptr->ether_type)); exit(1); } // copied from Steven's UNP ptr = eptr->ether_dhost; i = ETHER_ADDR_LEN; printf(" Destination Address: "); do{ printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++); }while(--i>0); printf("\n"); ptr = eptr->ether_shost; i = ETHER_ADDR_LEN; printf(" Source Address: "); do{ printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++); }while(--i>0); printf("\n"); return 0; }
int main(int argc, char **argv) { char *spoof_addr; char *site_name; char temp_site[128]; char *device; char filter[1024]; /* Capture filter */ char errbuf[PCAP_ERRBUF_SIZE]; /* Error buffer */ pcap_t* capdev; /* Capturing Device */ const u_char *packet = NULL; struct pcap_pkthdr pcap_hdr; /* Pcap packet header */ libnet_t *handler; /* Libnet handler */ int var; /* reserve the space for the spoofed packet */ memset(&spoofpacket, '\0', sizeof(struct sp)); /* get the spoofing IP address from input */ spoof_addr = "222.106.38.120"; site_name = "example.com"; if (argc >= 2) spoof_addr = argv[1]; if (argc >= 3) site_name = argv[2]; if (strncmp(site_name, "www", 3) != 0) { strncpy(temp_site, "www.", 4); strcpy(temp_site+4, site_name); site_name = temp_site; } /* get a device to sniff on */ device = pcap_lookupdev(errbuf); if (device == NULL) { printf("%s\n", errbuf); exit(1); } strcpy(filter, "udp dst port 53"); /* Setup for sniffering */ capdev = set_cap_dev(device, filter); printf("Sniffering on: %s\n", device); printf("Spoofing address: %s\n", spoof_addr); for (;;) { packet = pcap_next(capdev, &pcap_hdr); /* Grab a packet */ /**** USE: pcap function to grab next packet****/ if (packet == NULL) { continue; } // printf("Packet Length%d\n", pcap_hdr.len); //printf("Return value: %d", var); /* If the packet is a DNS query, create a packet */ if ((analyze_packet(packet, (int)pcap_hdr.caplen, spoof_addr, site_name)) == 1) { // printf("DNS packet found\n"); // Inject the spoofed DNS response // printf("Device: %s", device); spoof_dns(device); // printf("YAY! DNS packet sent\n"); // return 1; } } return 0; }
int main(int p_argc, const char** p_argv) { std::string fileName; std::string passwords; if (!parseCommandLine(p_argc, p_argv, fileName, passwords)) { return EXIT_FAILURE; } char errbuf[PCAP_ERRBUF_SIZE] = {}; pcap_t* handle = pcap_open_offline(fileName.c_str(), errbuf); if (handle == NULL) { std::cerr << "Failed to find the pcap file." << std::endl; return EXIT_FAILURE; } SessionParser parser; if (!parser.loadPasswords(passwords)) { return EXIT_FAILURE; } // read in the packets. Anything with a tcp payload hand to parser. const boost::uint8_t* packet = NULL; struct pcap_pkthdr header = { 0, 0, 0, 0}; while ((packet = pcap_next(handle, &header)) != NULL) { if (header.caplen != header.len) { std::cerr << "Skipping truncated packet." << std::endl; continue; } if (header.len <= 54) { std::cerr << "Skipping uninteresting packet." << std::endl; continue; } boost::uint16_t etherType = (packet[12] << 8) | packet[13]; if (etherType != 0x800) { std::cerr << "Skipping non-IPv4 packet." << std::endl; continue; } // skip to the IPv4 header packet += 14; boost::uint16_t length = (packet[2] << 8) | packet[3]; if (length > header.len) { std::cerr << "Bad length in IPv4 header." << std::endl; continue; } if (packet[9] != 0x06) { std::cerr << "Skipping non-TCP packet." << std::endl; continue; } boost::uint32_t srcAddress = (packet[12] & 0xff) << 24 | (packet[13] & 0xff) << 16 | (packet[14] & 0xff) << 8 | (packet[15] & 0xff); boost::uint16_t headerLength = (packet[0] & 0x0f) * 4; if ((headerLength + 20) > length) { std::cerr << "Bad header length in IPv4 header." << std::endl; continue; } // skip to the TCP header packet += headerLength; length -= headerLength; headerLength = packet[12] >> 2; if (headerLength > length) { std::cerr << "Bad length in the TCP header. " << std::endl; continue; } // skip to the payload packet += headerLength; length -= headerLength; if (length == 0) { continue; } parser.parse(packet, length, srcAddress); } pcap_close(handle); //close the pcap file return EXIT_SUCCESS; }
int live_capture() { int packet_count; char errbuf[PCAP_ERRBUF_SIZE]; u_char *packet; struct pcap_pkthdr h; pcap_t *_iface_capturer; pcap_t *_dumpfile; pcap_dumper_t *_dumper; int result = OK; if (signal(SIGINT, handle) == SIG_ERR) { printf("Error: Fallo al capturar la senal SIGINT.\n"); close_handlers(); return ERROR; } if ((_iface_capturer = pcap_open_live("eth0", 10, 0, 0, errbuf)) == NULL) { printf("Error: pcap_open_live(): %s %s %d.\n", errbuf, __FILE__, __LINE__); close_handlers(); return ERROR; } _dumpfile = pcap_open_dead(DLT_EN10MB, 1514); if (!_dumpfile) { printf("Error: pcap_open_dead(): %s %s %d.\n", errbuf, __FILE__, __LINE__); close_handlers(); return ERROR; } _dumper = pcap_dump_open(_dumpfile, "out.pcap"); if (!_dumper) { printf("Error: pcap_open_live(): %s %s %d.\n", errbuf, __FILE__, __LINE__); close_handlers(); return ERROR; } packet_count = 0; while (1) // Seguimos recibiendo hasta que recibimos una señal. { if ((packet = (u_int8_t *) pcap_next(_iface_capturer, &h)) == NULL) { printf("Error al capturar el paquete %s %d.\n", __FILE__, __LINE__); close_handlers(); return ERROR; } print_packet(&h, packet); pcap_dump((u_char *) _dumper, &h, packet); _packet_count++; } // No se llega nunca a esto, pero por si acaso. close_handlers(); return result; }
int main() { configure(); save_pid(); if (head != NULL) { pfree(head); } head = NULL; getData(); signal(SIGUSR1, sigroutine); /* if(head!=NULL); display(head); printf("%d\n",search(50505920)); if(head!=NULL); pfree(head); exit(0); */ char error_content[PCAP_ERRBUF_SIZE]; int http_len; struct pcap_pkthdr protocol_header; pcap_t *pcap_handle; const u_char *packet_content; bpf_u_int32 net_mask; bpf_u_int32 net_ip; char *net_interface; struct ether_header *eptr; //以太网帧 struct iphdr *ipptr; //ip数据报 struct in_addr addr; struct tcphdr *tcpptr; //tcp char *data; char hostbuf[500]; char getbuf[100]; char url[100]; unsigned int syn_ack_seq = 0; net_interface = conf.interface; pcap_lookupnet(net_interface, &net_ip, &net_mask, error_content); pcap_handle = pcap_open_live(net_interface, BUFSIZ, 1, 0, error_content); printf("Capture a packet from : %s\n", net_interface); while (1) { packet_content = pcap_next(pcap_handle, &protocol_header); if (packet_content == NULL) continue; eptr = (struct ether_header *) packet_content; int i = 0; memset(smac, 0, sizeof(smac)); for (i = 0; i < 6; i++) sprintf(smac, "%s%02x", smac, eptr->ether_shost[i]); if (ntohs(eptr->ether_type) == ETHERTYPE_IP) //http 基于tcp/ip,只捕获此类型的帧 { ipptr = (struct iphdr *) (packet_content + sizeof(struct ether_header)); //获得ip数据报的内存地址 if (ipptr->protocol == 6) //筛选出tcp报文 { tcpptr = (struct tcphdr *) (packet_content + sizeof(struct ether_header) + sizeof(struct iphdr)); if (ntohs(tcpptr->dest) == 80) { http_redirector(packet_content); } } } } pcap_close(pcap_handle); }
void *pcap_function(void *arg) { char *iface = (char *) arg; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t * handle = NULL; struct ieee80211_radiotap_header * rtap_head; struct ieee80211_header * eh; struct pcap_pkthdr header; const u_char * packet; u_char * mac; u_char first_flags; int offset = 0; char rssi; Element * dev_info; u_char alc_mac[6]; string_to_mac("00:73:8d:9e:cb:ab", alc_mac); // Open pcap handle to sniff traffic handle = pcap_open_live(iface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { printf("Could not open pcap on %s\n", iface); pthread_exit((void *) -1); } while (got_sigint == 0) { packet = pcap_next(handle, &header); if (!packet) continue; rtap_head = (struct ieee80211_radiotap_header *) packet; int len = (int) rtap_head->it_len[0] + 256 * (int) rtap_head->it_len[1]; eh = (struct ieee80211_header *) (packet + len); if ((eh->frame_control & 0x03) == 0x01) { mac = eh->source_addr; first_flags = rtap_head->it_present[0]; u_char* last_flag = &rtap_head->it_present[3]; offset = 8; offset += ((first_flags & 0x01) == 0x01) ? 8 : 0 ; offset += ((first_flags & 0x02) == 0x02) ? 1 : 0 ; offset += ((first_flags & 0x04) == 0x04) ? 1 : 0 ; offset += ((first_flags & 0x08) == 0x08) ? 4 : 0 ; offset += ((first_flags & 0x10) == 0x10) ? 2 : 0 ; /*while((*(last_flag) & 0x80) == 0x80) { offset += 4; last_flag += 4; }*/ rssi = *((char *) rtap_head + 18) - 0x100; if(rssi == 4) continue; printf("RADIOTAP Header Dump :\n"); printf("\t%x\n\t%x\n\t%x\t%x\n", rtap_head->it_version, rtap_head->it_pad, rtap_head->it_len[0], rtap_head->it_len[1]); printf("\t%x\t%x\t%x\t%x\n", rtap_head->it_present[0], rtap_head->it_present[1], rtap_head->it_present[2], rtap_head->it_present[3]); int i; for(i=0 ; i<len ; i+=4) { if(len-i > 4) { printf("\t%x\t%x\t%x\t%x\n", *( (u_char*)rtap_head + i), *( (u_char*)rtap_head + i+1), *( (u_char*)rtap_head + i+2), *( (u_char*)rtap_head + i+3)); } else { int j; for(j=i; j<len ; ++j) { printf("\t%x", *( (u_char*)rtap_head + j)); } break; } } printf("%d bytes -- %02X:%02X:%02X:%02X:%02X:%02X -- RSSI: %d dBm\n", len, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], (int) rssi); // We got some message issued by a terminal (FromDS=0,ToDS=1) sem_wait(&synchro); if ((dev_info = find_mac(rssi_list, mac)) == NULL) { dev_info = add_element(&rssi_list, mac); } clear_outdated_values(&dev_info->measurements); add_value(&dev_info->measurements, (int) rssi); if ((dev_info = find_mac(rssi_list, alc_mac)) != NULL) { print_element(dev_info); } sem_post(&synchro); } } pcap_close(handle); pthread_exit((void *) 0); }
int main(int argc, char** argv) { int ret = 0; int inum; int port; int saveFile = 0; int i = 0; int frame = ETHER_IF_FRAME_LEN; char err[PCAP_ERRBUF_SIZE]; char filter[32]; const char *server = NULL; struct bpf_program fp; pcap_if_t *d; pcap_addr_t *a; signal(SIGINT, sig_handler); #ifndef _WIN32 ssl_InitSniffer(); /* dll load on Windows */ #endif ssl_Trace("./tracefile.txt", err); if (argc == 1) { /* normal case, user chooses device and port */ if (pcap_findalldevs(&alldevs, err) == -1) err_sys("Error in pcap_findalldevs"); 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) err_sys("No interfaces found! Make sure pcap or WinPcap is" " installed correctly and you have sufficient permissions"); printf("Enter the interface number (1-%d): ", i); ret = scanf("%d", &inum); if (ret != 1) printf("scanf port failed\n"); if (inum < 1 || inum > i) err_sys("Interface number out of range"); /* Jump to the selected adapter */ for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++); pcap = pcap_create(d->name, err); if (pcap == NULL) printf("pcap_create failed %s\n", err); /* get an IPv4 address */ for (a = d->addresses; a; a = a->next) { switch(a->addr->sa_family) { case AF_INET: server = iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr); printf("server = %s\n", server); break; default: break; } } if (server == NULL) err_sys("Unable to get device IPv4 address"); ret = pcap_set_snaplen(pcap, 65536); if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap)); ret = pcap_set_timeout(pcap, 1000); if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap)); ret = pcap_set_buffer_size(pcap, 1000000); if (ret != 0) printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap)); ret = pcap_set_promisc(pcap, 1); if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap)); ret = pcap_activate(pcap); if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap)); printf("Enter the port to scan: "); ret = scanf("%d", &port); if (ret != 1) printf("scanf port failed\n"); SNPRINTF(filter, sizeof(filter), "tcp and port %d", port); ret = pcap_compile(pcap, &fp, filter, 0, 0); if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap)); ret = pcap_setfilter(pcap, &fp); if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap)); ret = ssl_SetPrivateKey(server, port, "../../certs/server-key.pem", FILETYPE_PEM, NULL, err); if (ret != 0) { printf("Please run directly from sslSniffer/sslSnifferTest dir\n"); } #ifdef HAVE_SNI { char altName[128]; printf("Enter alternate SNI: "); ret = scanf("%s", altName); if (strnlen(altName, 128) > 0) { ret = ssl_SetNamedPrivateKey(altName, server, port, "../../certs/server-key.pem", FILETYPE_PEM, NULL, err); if (ret != 0) { printf("Please run directly from " "sslSniffer/sslSnifferTest dir\n"); } } } #endif } else if (argc >= 3) { saveFile = 1; pcap = pcap_open_offline(argv[1], err); if (pcap == NULL) { printf("pcap_open_offline failed %s\n", err); ret = -1; } else { const char* passwd = NULL; /* defaults for server and port */ port = 443; server = "127.0.0.1"; if (argc >= 4) server = argv[3]; if (argc >= 5) port = atoi(argv[4]); if (argc >= 6) passwd = argv[5]; ret = ssl_SetPrivateKey(server, port, argv[2], FILETYPE_PEM, passwd, err); } } else { /* usage error */ printf( "usage: ./snifftest or ./snifftest dump pemKey" " [server] [port] [password]\n"); exit(EXIT_FAILURE); } if (ret != 0) err_sys(err); if (pcap_datalink(pcap) == DLT_NULL) frame = NULL_IF_FRAME_LEN; while (1) { static int packetNumber = 0; struct pcap_pkthdr header; const unsigned char* packet = pcap_next(pcap, &header); packetNumber++; if (packet) { byte data[65535+16384]; /* may have a partial 16k record cached */ if (header.caplen > 40) { /* min ip(20) + min tcp(20) */ packet += frame; header.caplen -= frame; } else continue; ret = ssl_DecodePacket(packet, header.caplen, data, err); if (ret < 0) printf("ssl_Decode ret = %d, %s\n", ret, err); if (ret > 0) { data[ret] = 0; printf("SSL App Data(%d:%d):%s\n", packetNumber, ret, data); } } else if (saveFile) break; /* we're done reading file */ } FreeAll(); return EXIT_SUCCESS; }
GOS_ERROR_CODE rtn_iw_sniff_start(void) { char errbuf[128]; char ifname[8]; char cmd[128]; char fifoname[64]; pcap_t *handle=NULL; pcap_dumper_t *pDump=NULL; struct pcap_pkthdr header; const u_char *packet; int fStatus = 0; UINT32 mode = gRtnParams.sniff_cfg.sniff_param.sniffMode|gRtnParams.sniff_cfg.sniff_param.sniffType; GOS_ERROR_CODE ret = GOS_OK; header = header; //for not use variable. memcpy(fifoname, AP_IW_SNIFF_DEF_FIFONAME, sizeof(fifoname)); //create fifo for sniff fStatus = mkfifo(fifoname, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH); if(fStatus == 0) { //change wifiX to monitor mode sprintf(ifname, "wifi%d", gRtnParams.sniff_cfg.sniff_param.radioIndex); sprintf(cmd, "iwpriv %s monitor %d", ifname, mode); VOS_ExecStr(0, cmd); RTN_LOG("Cmd:%s", cmd); //open pcap interface handle = pcap_open_live(ifname, BUFSIZ, 1, 0, errbuf); if(handle!=NULL) { gRtnParams.sniff_cfg.pcap_handle = handle; //open pcap_dump_open pDump = pcap_dump_open(handle, fifoname); if(pDump != NULL) { //for first test #if 0 RTN_LOG("----------wait....-------------------"); packet = pcap_next(handle, &header); /**/ RTN_LOG("Captured a packet with length of [%d]", header.len); /* */ #endif RTN_LOG("start pcap_loop -----"); gRtnParams.sniff_cfg.pcap_dump_handle = pDump; pcap_loop(handle, -1, pcap_dump, (unsigned char *)pDump); RTN_LOG("stop pcap_loop -----"); //close pcap dump handle, pcap_dump_close(pDump); gRtnParams.sniff_cfg.pcap_dump_handle = NULL; } else { RTN_LOG("Pcap_dump_open failed! %s\n", pcap_geterr(handle)); ret = GOS_ERR_IW_SNIFF_PCAPDUMP_OPEN_FAILED; } RTN_LOG("Close pcap -----"); //close pcap hanlde. pcap_close(handle); gRtnParams.sniff_cfg.pcap_handle = NULL; unlink(fifoname); // close the monitor mode sprintf(cmd, "iwpriv wifi%d monitor 0", gRtnParams.sniff_cfg.sniff_param.radioIndex); VOS_ExecStr(0, cmd); RTN_LOG("Cmd:%s", cmd); } else { ret = GOS_ERR_IW_SNIFF_PCAP_OPEN_FAILED; RTN_LOG("----------pcap_open_live return NULL: %s-------------------", errbuf); } } else { ret = GOS_ERR_IW_SNIFF_FIFO_CREATE_FAILED; RTN_LOG("create fifo failed. %s\n", strerror(errno)); } gRtnParams.sniff_cfg.sniff_task = VOS_TASK_ID_INVALID; RTN_LOG("----------natrual end---------"); VOS_TerminateTask(); return ret; }
int main(int argc, char *argv[]) { pcap_if_t *all_devs; pcap_if_t *dev; char err_buf[PCAP_ERRBUF_SIZE]; char dev_name[16]; pcap_t *handle; /* Session handle */ bpf_u_int32 mask; bpf_u_int32 net; struct pcap_pkthdr header; /* The header that pcap gives us */ const u_char *packet; /* The actual packet */ /* Find all the devices */ if (pcap_findalldevs(&all_devs, err_buf) == -1) { fprintf(stderr, "Error in pcap_findalldevs(): %s\n", err_buf); exit(EXIT_FAILURE); } /* Loop all the devices */ printf("\nDevices in this computer:\n"); for (dev = all_devs; dev != NULL; dev = dev->next) print_dev_info(dev); printf("Please enter the device name which you want to open:\n>> "); fgets(dev_name, sizeof(dev_name), stdin); /* Remove the '\n' in the buf */ dev_name[strlen(dev_name) - 1] = '\0'; /* Get the net id and the mask */ if (pcap_lookupnet(dev_name, &net, &mask, err_buf) == -1) { fprintf(stderr, "Can't get netmask for device %s: %s\n", dev_name, err_buf); net = 0; mask = 0; } /* Open the device */ handle = pcap_open_live(dev_name, 65535, 1, 0, err_buf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev_name, err_buf); exit(EXIT_FAILURE); } /* if (pcap_datalink(handle) != DLT_EN10MB) { fprintf(stderr, "Device %s doesn't provide Ethernet headers - " "not supported\n", dev_name); exit(EXIT_FAILURE); } */ printf("\nCapture Device: %s\n", dev_name); printf("------------------------------\n\n"); int number = 0; while (1) { /* Grab a packet */ packet = pcap_next(handle, &header); if (packet == NULL) continue; printf("Packet length: %d\n", header.len); printf("Number of bytes: %d\n", header.caplen); printf("Recieved time: %s\n", ctime((const time_t *) &(header.ts.tv_sec))); ++number; if (number >= 10) break; } /* */ number = 0; pcap_loop(handle, -1, got_packet, (u_char *) &number); /* Close device */ pcap_close(handle); return 0; }
int main (int argc, char **argv) { pcap_t *pcap1, *pcap2, *pcapout; pcap_dumper_t *popen; struct pcap_pkthdr header1, header2; const u_char *packet1, *packet2; char errbuf[256]; struct timeval tv1, tv2, tvdiff, tvwork; char *output = NULL; char *input1 = NULL; char *input2 = NULL; int ch; if (argc < 3) { usage(argv[0]); } while ((ch = getopt(argc, argv, "ho:1:2:")) != EOF) { switch ((char) ch) { case 'o': output = optarg; break; case 'h': usage(argv[0]); break; case '1': input1 = optarg; break; case '2': input2 = optarg; break; } } if (input1 == NULL || input2 == NULL || output == NULL) { usage(argv[0]); exit(-1); } if((pcap1 = pcap_open_offline(input1, errbuf)) == NULL) { printf("Error: %s\n", errbuf); exit(-1); } if((pcap2 = pcap_open_offline(input2, errbuf)) == NULL) { printf("Error: %s\n", errbuf); exit(-1); } if((pcapout = pcap_open_dead(DLT_RAW, SNAPLEN)) == NULL) { printf("Error: %s\n", errbuf); exit(-1); } if((popen = pcap_dump_open(pcap1, output) ) == NULL) { printf("Error! %s\n", pcap_geterr(pcapout)); exit(-1); } if(( packet1 = pcap_next(pcap1, &header1) ) == NULL) { printf("Error: no packets in capture file %s\n", input1); exit(-1); } if(( packet2 = pcap_next(pcap2, &header2)) == NULL) { printf("Error: no packets in capture file %s\n", input2); exit(-1); } tv2 = header2.ts; while(packet1 != NULL) { pcap_dump((u_char *)popen, &header1, packet1); packet1 = pcap_next(pcap1, &header1); } tv1 = header1.ts; timersub(&tv1, &tv2, &tvdiff); printf("Diff: %2.6f\n", (double)tvdiff.tv_usec/1000000 + tvdiff.tv_sec ); while (packet2 != NULL) { timeradd(&header2.ts, &tvdiff, &tvwork); header2.ts = tvwork; pcap_dump((u_char *)popen, &header2, packet2); packet2 = pcap_next(pcap2, &header2); } pcap_dump_close(popen); pcap_close(pcap1); pcap_close(pcap2); pcap_close(pcapout); exit(0); }
int main(){ pcap_t *pt; char *dev; char errbuf[128]; struct bpf_program fp; bpf_u_int32 maskp,netp; int ret,i=0,inum; int pcap_time_out=5; char filter[128]; unsigned char *packet; struct pcap_pkthdr hdr; pcap_if_t *alldevs = NULL,*d; pid_t pid; char ch[10],str = 'n'; attHead att_head; head = init_ip_list(head); att_head = init_attHead(); if(pcap_findalldevs(&alldevs,errbuf)==-1) { fprintf(stderr,"find interface failed!\n"); return; } for(d=alldevs;d;d=d->next){ printf("%d. %s\n",++i,d->name); if(d->description) printf("(%s)\n",d->description); else printf("(no description available)\n"); } if(i==1) dev=alldevs->name; else { printf("input a interface:(1-%d)",i); scanf("%d",&inum); if(inum<1||inum>i) { printf("interface number out of range\n"); return; } for(d=alldevs,i=1;i<inum;d=d->next,i++); dev=d->name; } printf("dev:%s\n",dev); ret=pcap_lookupnet(dev,&netp,&maskp,errbuf); printf(""); if(ret==-1){ fprintf(stderr,"%s\n",errbuf); return; } pt=pcap_open_live(dev,BUFSIZ,1,pcap_time_out,errbuf); if(pt==NULL){ fprintf(stderr,"open error :%s\n",errbuf); return; } while(1) { printf("if you want to quit press y,else press any other key!\n"); scanf("%c",&str); if(str == 'y')break; pid = vfork(); if(pid < 0){ printf("fail to fork\n"); }else if(pid == 0){ if(signal(SIGALRM,timer_handler) == SIG_ERR){ perror("can't set handler for SIGALRM\n"); exit(0); } alarm(1800); while(1){ packet=(char *)pcap_next(pt,&hdr); if(packet==NULL) continue; else{ printf("\n\n\n"); printf("get a packet\n"); ethernet_packet_callback(NULL,&hdr,packet); num++; printf("\n"); if(flag == arp){ insert_data(att_head,num,"arp","xxxxxxxx","broadcast"); // printMemory(att_head); flag = 0; } else{ switch(flag){ case ip: strcpy(ch,"ip");break; case tcp: strcpy(ch,"tcp");break; case udp: strcpy(ch,"udp");break; case http: strcpy(ch,"http");break; case oicq: strcpy(ch,"oicq");break; case webqq: strcpy(ch,"webqq");break; case msnms: strcpy(ch,"msnms");break; default: strcpy(ch,"xxx"); strcpy(srcip,"xxxxxxxx"); strcpy(desip,"xxxxxxxx"); other_num++; other_bytes = other_bytes+hdr.len; break; } insert_data(att_head,num,ch,srcip,desip); // printMemory(att_head); flag = 0; } } printf("\n"); printf("其他包的总数:%d 其他包的总字节数:%ld\n",other_num,other_bytes); printf("ip包的总数:%d ip包的总字节数:%ld\n",ip_num,ip_bytes); printf("arp包的总数:%d arp包的总字节数:%ld\n",arp_num,arp_bytes); printf("tcp包的总数:%d tcp包的总字节数:%ld\n",tcp_num,tcp_bytes); printf("udp包的总数:%d udp包的总字节数:%ld\n",udp_num,udp_bytes); printf("oicq包的总数:%d oicq包的总字节数:%ld\n",oicq_num,oicq_bytes); printf("http包的总数:%d http包的总字节数: %ld\n",http_num,http_bytes); printf("web qq包的总数:%d web qq包的总字节数: %ld\n",webqq_num,webqq_bytes); printf("msnms包的总数:%d msnms包的总字节数: %ld\n",msnms_num,msnms_bytes); display_ip_list(head); } } else{ delete_ip_list(head,1); if(wait(NULL) == -1){ printf("fail to wait\n"); exit(1); } } } pcap_close(pt); saveTable(att_head); free_ip_list(head); free_data(att_head); return 0; /* pt = pcap_open_offline("msn.pcap",errbuf); if(pt == NULL){ printf("ERROR:could not open pcap file: %s\n",errbuf); exit(-1); } pcap_loop(pt,-1,ðernet_packet_callback,NULL); pcap_close(pt); return 0;*/ }
int setup_sched(struct tcp_sched* sched){ input_addr sip, dip; /* Source & Destination IP */ input_addr local_ip, remote_ip; /* ip address of client and server*/ /*temporary packet buffers*/ struct pcap_pkthdr header; // The header that pcap gives us const u_char *packet; // The actual packet pcap_t *local_handle; unsigned int pkt_counter=0; ether_hdr *etherhdr = NULL; tcp_hdr *tcphdr = NULL; ipv4_hdr *iphdr = NULL; local_ip.byte1=0; local_ip.byte2=0; local_ip.byte3=0; local_ip.byte4=0; remote_ip.byte1=0; remote_ip.byte2=0; remote_ip.byte3=0; remote_ip.byte4=0; unsigned int size_ip, i = 0; unsigned int size_tcp; unsigned int size_payload; char errbuf[PCAP_ERRBUF_SIZE]; unsigned int flags=0; bool remote = false; /* flags to test if data is from 'cleint'=local or 'server'=remote */ bool local = false; local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/ if (local_handle == NULL) { fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf); return(2); } /*Before sending any packet, setup the schedule with the proper parameters*/ while((packet = pcap_next(local_handle,&header))) { pkt_counter++; /*increment number of packets seen*/ memcpy(&sched[i].pkthdr, &header, sizeof(struct pcap_pkthdr)); //sched[i].len = header.len; //sched[i].caplen = header.caplen; sched[i].packet_ptr = safe_malloc(sched[i].pkthdr.len); memcpy(sched[i].packet_ptr, packet, sched[i].pkthdr.len); /* extract necessary data */ etherhdr = (ether_hdr*)(sched[i].packet_ptr); iphdr = (ipv4_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET); size_ip = iphdr->ip_hl << 2; if (size_ip < 20) { printf("ERROR: Invalid IP header length: %u bytes\n", size_ip); return 0; } tcphdr = (tcp_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip); size_tcp = tcphdr->th_off*4; if (size_tcp < 20) { printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp); return 0; } /* payload = (u_char *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip + size_tcp); */ size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp)); /* Source IP and Destination IP */ sip = iphdr->ip_src; dip = iphdr->ip_dst; flags = tcphdr->th_flags; if (flags == TH_SYN){ /* set IPs who's local and who's remote based on the SYN flag */ local_ip = sip; remote_ip = dip; } /*Compare IPs to see which packet is this comming from*/ if(compip(&local_ip, &remote_ip, &sip)==LOCAL_IP_MATCH){ local = true; remote = false; } if(compip(&local_ip, &remote_ip, &sip)==REMOTE_IP_MATCH){ local = false; remote = true; } /* Setup rest of Schedule, parameter by parameter */ /* Refer to header file for details on each of the parameters */ sched[i].etherhdr = etherhdr; sched[i].iphdr = iphdr; sched[i].tcphdr = tcphdr; sched[i].size_ip = size_ip; sched[i].size_tcp = size_tcp; sched[i].size_payload = size_payload; sched[i].sent_counter = 0; /* Do the following only for the first packet (SYN)*/ if(i==0){ sched[i].length_last_ldata = 0; sched[i].length_curr_ldata = 0; sched[i].length_last_rdata = 0; sched[i].length_curr_rdata = 0; sched[i].local = true; sched[i].remote = false; sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq); sched[i].curr_lack = 0; sched[i].exp_rseq = 0; /* Keep track of previous remote seq & ack #s*/ sched[i].exp_rack = 0; } /* Local Packet operations */ else if(local){ sched[i].length_last_ldata = sched[i-1].length_curr_ldata; sched[i].length_curr_ldata = size_payload; sched[i].length_last_rdata = sched[i-1].length_curr_rdata; sched[i].length_curr_rdata = 0; sched[i].local = true; sched[i].remote = false; sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq); sched[i].curr_lack = ntohl(sched[i].tcphdr->th_ack); sched[i].exp_rseq = sched[i-1].exp_rseq; /* Keep track of previous remote seq & ack #s*/ sched[i].exp_rack = sched[i-1].exp_rack; } /* Remote Packet operations */ else if(remote){ sched[i].length_last_ldata = sched[i-1].length_curr_ldata; sched[i].length_curr_ldata = 0; sched[i].length_last_rdata = sched[i-1].length_curr_rdata; sched[i].length_curr_rdata = size_payload; sched[i].local = false; sched[i].remote = true; sched[i].curr_lseq = sched[i-1].curr_lseq; sched[i].curr_lack = sched[i-1].curr_lack; sched[i].exp_rseq = ntohl(sched[i].tcphdr->th_seq); /* Keep track of previous remote seq & ack #s*/ sched[i].exp_rack = ntohl(sched[i].tcphdr->th_ack); /* Setup global variable where remote FIN-ACK exists*/ if(flags == (TH_FIN|TH_ACK)) finack_rindex = i; //printf("REMOTE --------%d\n",i+1); } i++; /* increment schedule index */ } /*end internal loop for reading packets (all in one file)*/ pcap_close(local_handle); /*close the pcap file*/ return pkt_counter; /* Return number of packets scheduled */ }
void query_processor(){ char str[50]; char subquery1[50],subquery2[50]; char bpf_query[50]; struct bpf_program bpf_prog; printf("\nIndex Query Options for fields:\n SrcIP or DstIP or SrcPort or DstPort or Protocol\n Protocol=0 for TCP else 1 for UDP\n"); printf("\nExample: protocol=1\n"); printf("\nPlease Enter Your Index Query: "); scanf("%s",str); printf("\nYour Index Query Was: %s",str); char* pos; //OR if((pos=strchr(str,';'))!=NULL){ strncpy(subquery1,str,pos-str); subquery1[pos-str]='\0'; strncpy(subquery2,str+(pos-str)+1,str+strlen(str)-pos); printf("\nSubquery1: %s",subquery1); printf("\nOR"); printf("\nSubquery2: %s\n",subquery2); single_query(subquery1,1); single_query(subquery2,2); int i; for(i=0;i<packet_count;i++){ query_result[i]=sub1result[i] || sub2result[i]; } } //AND else if((pos=strchr(str,':'))!=NULL){ strncpy(subquery1,str,pos-str); subquery1[pos-str]='\0'; strncpy(subquery2,str+(pos-str)+1,str+strlen(str)-pos); printf("\nSubquery1: %s",subquery1); printf("\nAND"); printf("\nSubquery2: %s\n",subquery2); single_query(subquery1,1); single_query(subquery2,2); int i; for(i=0;i<packet_count;i++){ query_result[i]=sub1result[i] && sub2result[i]; } } //Single big query else{ single_query(str,0); } //Populate the indirection from the indirection array file FILE *indir_file; indir_file=fopen("resources/Indirection.txt","r"); int i; int indir_arr[1000]; char line[1000]; for(i=0;i<packet_count;i++) { fgets(line,1000,indir_file); int j=0; int count=0; while(line[j]!='\n'){ count=count*10+ line[j]-48; j++; } indir_arr[i] = count; } int offsets_arr_length=0; for(i=0;i<packet_count;i++) { if(query_result[i]==1) { offsets[offsets_arr_length++]=indir_arr[i]; } } char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; const u_char *packet; struct pcap_pkthdr hdr; const struct ip* iphdr; const struct sniff_tcp* tcp; const struct UDP_hdr *udp; descr = pcap_open_offline("1.cap",errbuf); if(descr == NULL) { printf("pcap_open_offline(): %s\n",errbuf); exit(1); } printf("\n%d packets met with the requirements of index query\n",offsets_arr_length); printf("\nPlease Enter Your BPF query:"); getchar(); gets(bpf_query); printf("Your BPF query was: %s\n",bpf_query); printf("\nSatisfying packets:\n"); for(k=0;k<offsets_arr_length;k++) { fseek(pcap_file(descr),offsets[k],SEEK_SET); if (pcap_compile(descr, &bpf_prog, (const char*)bpf_query, 0, PCAP_NETMASK_UNKNOWN) == -1) { printf("Couldn't parse filter %s: %s\n", bpf_query, pcap_geterr(descr)); } if (pcap_setfilter(descr, &bpf_prog) == -1) { printf("Couldn't install filter %s: %s\n", bpf_query, pcap_geterr(descr)); } packet = pcap_next(descr,&hdr); //printf("\n%d",offsets[k]+16+hdr.len); //printf("\n%d",ftell(pcap_file(descr))); if(packet!=NULL && offsets[k]+16+hdr.len ==ftell(pcap_file(descr))) { iphdr = (struct ip*)(packet + sizeof(struct ether_header)); printf("\nPacket Number:%d\n",k+1); printf("Packet Found at offset:%d\n",offsets[k]); printf("Source:%s\n",inet_ntoa(iphdr->ip_src)); printf("Destination:%s\n",inet_ntoa(iphdr->ip_dst)); if(iphdr->ip_p==6){ printf("Protocol:TCP\n"); tcp = (struct sniff_tcp*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); printf("Source Port:%d\n",ntohs(tcp->th_sport)); printf("Destination Port:%d\n",ntohs(tcp->th_dport)); } else if(iphdr->ip_p==17){ printf("Protocol:UDP\n"); udp=(struct UDP_hdr*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); printf("Source Port:%d\n",ntohs(udp->uh_sport)); printf("Destination Port:%d\n",ntohs(udp->uh_dport)); } } printf("\n"); } }
int main(int argc, char **argv) { int i; char *dev; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; const u_char *packet; struct pcap_pkthdr hdr; /* pcap.h */ struct ether_header *eptr; /* net/ethernet.h */ u_char *ptr; /* printing out hardware header info */ dev = pcap_lookupdev(errbuf); if (dev == NULL) { printf("%s\n",errbuf); exit(1); } printf("DEV: %s\n",dev); /* get packet capture descriptor from capture. Note if you change "prmisc" param to anything other than zero, you will get all packets your device sees, whether they are intendeed for you or not!! Be sure you know the rules of the network you are running on before you set your card in promiscuous mode or you could get yourself in serious doo doo!!! (also need to be root to run in promisuous mode) */ descr = pcap_open_live(dev,BUFSIZ,0,-1,errbuf); if (descr == NULL) { printf("pcap_open_live(): %s\n",errbuf); exit(1); } packet = pcap_next(descr,&hdr); if (packet == NULL) { printf("Didn't grab packet\n"); exit(1); } printf("Grabbed packet of length %d\n",hdr.len); printf("Recieved at ..... %s\n",ctime((const time_t*)&hdr.ts.tv_sec)); printf("Ethernet address length is %d\n",ETHER_HDR_LEN); eptr = (struct ether_header *) packet; if (ntohs (eptr->ether_type) == ETHERTYPE_IP) { printf("Ethernet type hex:%x dec:%d is an IP packet\n", ntohs(eptr->ether_type), ntohs(eptr->ether_type)); } else if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) { printf("Ethernet type hex:%x dec:%d is an ARP packet\n", ntohs(eptr->ether_type), ntohs(eptr->ether_type)); } else { printf("Ethernet type %x not IP", ntohs(eptr->ether_type)); exit(1); } ptr = eptr->ether_dhost; i = ETHER_ADDR_LEN; printf(" Destination Address: "); do { printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++); } while(--i>0); printf("\n"); ptr = eptr->ether_shost; i = ETHER_ADDR_LEN; printf(" Source Address: "); do { printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++); } while(--i>0); printf("\n"); return 0; }
int main(int argc, const char *argv[]) { char err[PCAP_ERRBUF_SIZE]; const u_char *b; struct pcap_pkthdr h; pcap_t *aPCapIN; pcap_dumper_t* pw; UInt32 s; int ret; header* f; UInt8 x[3000], key[16] = {0}; RC4 rc; UInt8* data; int framelen; if (argc!=3) { cerr << "usage: " << argv[0] << " input output\n"; return -1; } aPCapIN=pcap_open_offline(argv[1],err); if (aPCapIN==NULL) { cerr << "Could not open dump file:" << err << "\n"; return -2; } pw=pcap_dump_open(aPCapIN,argv[2]); if (aPCapIN==NULL) { cerr << "Could not open output file.\n"; ret=-3; goto error1; } setupIdentity(); //initialized the RC4 sboxes memcpy(key+3,KEY,KEYSIZE); b=pcap_next(aPCapIN,&h); while(b) { memcpy(x,b,h.caplen); f=(header*)x; if (((f->frameControl&IEEE80211_TYPE_MASK)==IEEE80211_TYPE_DATA)&&(h.caplen>=32)) { if (f->frameControl & IEEE80211_DIR_MASK == IEEE80211_DIR_DSTODS) { data = f->data + 4; framelen = h.caplen - 4; } else { data = f->data; framelen = h.caplen; } memcpy(key, data, 3); RC4InitWithKey(&rc, key, KEYSIZE+3); for(s = 4;s < (framelen-24);s++) data[s-4]= data[s] ^ step(&rc); if (doFCS(data, framelen-28) == 0xdebb20e3) { f->frameControl &= ~IEEE80211_WEP; h.caplen -= 8; h.len -= 8; pcap_dump((u_char*)pw,&h,x); cout << "decrypted packet\n"; } else cout << "FCS failed.\n"; } b=pcap_next(aPCapIN,&h); } ret=0; pcap_dump_close(pw); error1: pcap_close(aPCapIN); return ret; }
int main (int argc, char *argv[]) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *dh; struct bpf_program filter; bpf_u_int32 mask; bpf_u_int32 net; struct pcap_pkthdr header; const u_char *packet; if (parse_config (argv[0])) { printf ("Failed to parse config file, leaving\n"); return -1; } if (process_parms (argc,argv)) { printf ("Bad parameters, leaving\n"); return -1; } if (devname==NULL) { printf ("A device name (such as eth0) is required\n"); exit (-1); } if (daemonize) { switch (go_daemon()) { case -1: daemonize=0; log_debug (0, "Failed to become a daemon!"); exit (-1); case 1: // We are the parent. Exit and let the child on its own exit (0); case 0: log_debug (3, "Successfully became a daemon."); break; default: daemonize=0; log_debug (0, "This is a bug!"); exit (-1); } } else strcpy (debuglogdir,""); log_debug (3, "Getting address and mask for device %s...",devname); if (pcap_lookupnet(devname, &net, &mask, errbuf)==-1) { log_debug (0, "error [%s]",errbuf); exit (-1); } log_debug (3, "OK"); log_debug (3, "Opening device..."); dh = pcap_open_live (devname, 65535, promisc, 1000, errbuf); if (dh==NULL) { log_debug (0, "error [%s]",errbuf); exit (-1); } log_debug (3, "OK"); if (data_offset == -1) /* User didn't force an offset, try to find out */ { char *dln; log_debug (3, "Checking datalink type..."); if (get_datalink_info (dh, &dln, &data_offset)) { log_debug (0, "not supported. Please play with the -offset option (see docs)"); exit (-1); } log_debug (3, "OK, %s, offset = %d", dln, data_offset); } else { log_debug (1, "Using an user defined offset [%d], for datalink type [%d], good luck!", data_offset, get_datalink_type(dh)); } log_debug (3, "Compiling filter [%s]...",filter_app); if (pcap_compile(dh, &filter, filter_app, 0, net)==-1) { log_debug (0, "error: Couldn't parse filter %s", filter_app); exit (-1); } log_debug (3, "OK"); log_debug (3, "Setting filter..."); if (pcap_setfilter(dh, &filter)==-1) { log_debug (0, "error [%s]",errbuf); exit (-1); } log_debug (3, "OK"); log_debug (3, "Entering capture loop..."); if (chatlogdir[0]!=0) mkdir (chatlogdir,0700); if (debuglogdir[0]!=0) mkdir (debuglogdir,0700); long packet_count = 0; while (1) { packet = pcap_next(dh, &header); if (packet==NULL) { log_debug (5, "No packet received"); continue; } process_packet (++packet_count, &header,packet); } }