),
struct ether_header *eptr;//以太网字头
u_char *ptr;
int i;
if (packet == NULL)//packet里面有内容,可以证明上面的猜想,
{
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;//得到以太网字头
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);
//以上关于ip、tcp的结构信息请查询/usr/include/linux/ip.h | tcp.h
data = (char*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)
+sizeof(struct tcphdr));//得到数据包里内容,不过一般为乱码。
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);
//第三个参数,1为混杂模式;0为非混杂模式
//BUFSIZ同PCAP_ERRBUF_SIZE一样,均为库文件已经定义好的,不推荐使用
if (descr == NULL)
{
printf ("pcap_open_live(): %s/n", errbuf);
exit (1);
}
pcap_loop (descr, atoi(argv[1]), my_callback, NULL);//调用回调函数
printf("Hello world/n");
return (0);
}
关于过滤机制,以后再写
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。