), struct ether_header *eptr;//以太網(wǎng)字頭 u_char *ptr; int i; if (packet == NULL)//packet里面有內(nèi)容,可以證明上面的猜想, { printf ("Didn't grab packet!/n"); exit (1); } printf ("/n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$/n"); printf ("Grabbed packet of length %d/n", hdr.len); printf ("Received 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;//得到以太網(wǎng)字頭 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); } } ptr = eptr->ether_dhost; i = ETHER_ADDR_LEN; printf ("i=%d/n", i); printf ("Destination Address: "); do { printf ("%s%x", (i == ETHER_ADDR_LEN)?"":":", *ptr++); }while(--i>0); printf ("/n"); //printf ("%x/n",ptr); 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"); printf ("Now decoding the IP packet./n"); ipptr = (struct iphdr*) (packet+sizeof(struct ether_header));//得到ip包頭 printf ("the IP packets total_length is :%d/n", ipptr->tot_len); printf ("the IP protocol is %d/n", ipptr->protocol); addr.s_addr = ipptr->daddr; printf ("Destination IP: %s/n", inet_ntoa(addr)); addr.s_addr = ipptr->saddr; printf ("Source IP: %s/n", inet_ntoa(addr)); printf ("Now decoding the TCP packet./n"); tcpptr = (struct iphdr*)(packet+sizeof(struct ether_header) +sizeof(struct iphdr));//得到tcp包頭 printf ("Destination port : %d/n", tcpptr->dest); printf ("Source port : %d/n", tcpptr->source); printf ("the seq of packet is %d/n", tcpptr->seq); //以上關(guān)于ip、tcp的結(jié)構(gòu)信息請(qǐng)查詢/usr/include/linux/ip.h | tcp.h data = (char*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr) +sizeof(struct tcphdr));//得到數(shù)據(jù)包里內(nèi)容,不過一般為亂碼。 printf ("the content of packets is /n%s/n",data); } 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; struct ether_header *eptr; if (argc != 2) { fprintf (stdout, "Usage: %s numpackets/n", argv[0]); return 0; } dev = pcap_lookupdev (errbuf); if (dev == NULL) { printf ("%s/n", errbuf); exit (1); } descr = pcap_open_live (dev, BUFSIZ, 1, -1, errbuf); //第三個(gè)參數(shù),1為混雜模式;0為非混雜模式 //BUFSIZ同PCAP_ERRBUF_SIZE一樣,均為庫文件已經(jīng)定義好的,不推薦使用 if (descr == NULL) { printf ("pcap_open_live(): %s/n", errbuf); exit (1); } pcap_loop (descr, atoi(argv[1]), my_callback, NULL);//調(diào)用回調(diào)函數(shù) printf("Hello world/n"); return (0); } 關(guān)于過濾機(jī)制,以后再寫 |
|