#include #include #include #include #include #include #include #include /* * To compile : * * gcc -o extract extract.c -lpcap * */ u_int baseseq; int output; void handle_packet(u_char *args, const struct pcap_pkthdr* header, const u_char* packet) { struct ether_header *ethernet_frame; struct ip *ip_packet; struct tcphdr *tcp_packet; u_int ip_header_len, ip_len, tcp_header_len, len; off_t position; ethernet_frame = (struct ether_header *)packet; if(ntohs(ethernet_frame->ether_type) == ETHERTYPE_IP) { packet += sizeof(struct ether_header); ip_packet = (struct ip*)(packet); ip_header_len = ip_packet->ip_hl * 4; ip_len = ntohs(ip_packet->ip_len); if (ip_packet->ip_p == IPPROTO_TCP) { packet += ip_header_len; tcp_packet=(struct tcphdr *)(packet); tcp_header_len = tcp_packet->doff * 4; packet += tcp_header_len; if(baseseq==0) { baseseq=ntohl(tcp_packet->seq); } len = ip_len - ip_header_len - tcp_header_len; if(len>0) { position=(ntohl(tcp_packet->seq)-baseseq)-1; lseek(output,position,SEEK_SET); write(output,packet,len); } } } } void die(char *msg, int code) { fprintf(stderr,"%s\n",msg); exit(code); } #define BUFSIZE 1024 int main(int argc, char **argv) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *descr; struct bpf_program filter; bpf_u_int32 netp; u_char* args = NULL; int input,nbread; char filename[16],buf[BUFSIZE+1]; baseseq=0; if( ( descr = pcap_open_offline("-",errbuf) ) == NULL) { fprintf(stderr,"Error in pcap_open_offline :\n%s\n",errbuf); exit(1); } if(pcap_compile(descr,&filter,argv[1],0,netp) == -1) { die("Error in pcap_compile",1); } if(pcap_setfilter(descr,&filter) == -1) { die("Error in set_filtern",1); } strcpy(filename,"/tmp/edaXXXXXX"); mktemp(filename); if( (output=creat(filename,0600)) == -1) { die("Failed to create file",1); } pcap_loop(descr,-1,handle_packet,args); close(output); if( (input=open(filename,O_RDONLY)) == -1) { die("Failed to open file",1); } while((nbread=read(input,buf,BUFSIZE))>0) { write(1,buf,nbread); } unlink(filename); return(0); }