- 论坛徽章:
- 0
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pcap.h>
#include<string.h>
#include<time.h>
#include<error.h>
struct ether_header
{
unsigned char source[6];
unsigned char dest[6];
unsigned int type;
};
struct ip_header
{
#ifdef WORDS_BIGENDIAN
u_int8_t ip_version:4,
ip_header_length:4;
#else
u_int8_t ip_header_length:4,
ip_version:4;
#endif
u_int8_t ip_tos; /*type of service */
u_int16_t ip_length; /*length */
u_int16_t ip_id; /*identity */
u_int16_t ip_off; /* offset */
u_int8_t ip_ttl; /*time to live*/
u_int8_t ip_protocol; /* type of protocol*/
u_int16_t ip_chechsum; /* chechsum */
struct in_addr source;
struct in_addr dest;
};
void packet_callback(unsigned char* argument,const struct pcap_pkthdr* packet_header, const unsigned char* packet_content)
{
struct ether_header* eptr;
struct ip_header* iptr;
eptr=(struct ether_header*) packet_content;
switch(ntohs(eptr->type))
{
case 0x0800 :/*IP*/
iptr=(struct ip_header*)(packet_content+14);
switch(iptr->ip_protocol)
{
case 6: /* TCP */
printf("%s %s \n", inet_ntoa(iptr->source),inet_ntoa(iptr->dest));
break;
}
break;
}
return ;
};
int main(int argc ,char* argv[])
{
char errbuf[PCAP_ERRBUF_SIZE]; //store the information for error
char* net_interface; //store the chars of net interface
bpf_u_int32 ipaddr;
bpf_u_int32 ipmask;
pcap_t* pcap_handle; //the handle of pcap
struct bpf_program bpf_filter;
char bpf_filter_string[]="tcp"; //the filter string
net_interface=pcap_lookupdev(errbuf);
pcap_lookupnet(net_interface,&(ipaddr),&(ipmask),errbuf);
pcap_handle=pcap_open_live(net_interface,BUFSIZ,1,0,errbuf);
if(pcap_handle==NULL)
{
printf("Error in function pcap_open_live. Exiting ...\n");
exit(1);
}
if(pcap_compile(pcap_handle,&bpf_filter,bpf_filter_string,0,ipaddr)==-1)
{
printf("Error in function pcap_compile. Exiting ...\n");
exit(1);
}
if(pcap_setfilter(pcap_handle,&bpf_filter)==-1)
{
printf("Error in function pcap_setfilter. Exiting ...\n");
exit(1);
}
pcap_loop(pcap_handle,-1,packet_callback,NULL);
pcap_close(pcap_handle);
return 0;
} |
|