/* libpcap programming example. Captures packets and prints source and destination addresses and packet length Usage: pt Compiling: gcc -lpcap -o pt pcap.c Author: Maxim V Tretjyakov Version: 0.2 Date: понедельник, 25 октября 2004 г. 18:37:35 */ #include #include #include #include #include #define ETHER_ADDR_LEN 6/sizeof(u_char) struct ethernet_header { u_char ether_shost[ETHER_ADDR_LEN]; u_char ether_dhost[ETHER_ADDR_LEN]; u_short ether_type; }; struct ip { #if BYTE_ORDER == LITTLE_ENDIAN u_int ip_hl:4, /* header length */ ip_v:4; /* version */ #endif #if BYTE_ORDER == BIG_ENDIAN u_int ip_v:4, /* version */ ip_hl:4; /* header length */ #endif u_char ip_tos; /* type of service */ u_short ip_len; /* total length */ u_short ip_id; /* identification */ u_short ip_off; /* fragment offset field */ #define IP_RF 0x8000 /* reserved fragment flag */ #define IP_DF 0x4000 /* dont fragment flag */ #define IP_MF 0x2000 /* more fragments flag */ #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ u_char ip_ttl; /* time to live */ u_char ip_p; /* protocol */ u_short ip_sum; /* checksum */ struct in_addr ip_src,ip_dst; /* source and dest address */ } __packed; struct packet_t { struct ethernet_header eh; struct ip iph; struct tcphdr tcph; }; const char iface[] = "bfe0"; char buff[BUFSIZ]; pcap_t * handle; char errbuf[PCAP_ERRBUF_SIZE]; struct protoent * pe; void pcap_callback(u_char * useless, const struct pcap_pkthdr* pkthdr, const u_char * packetpj); int main() { struct bpf_program filter; char filter_app[] = "net 172.16.3.0/24"; bpf_u_int32 mask; bpf_u_int32 net; const u_char * packet; char * x; pe = getprotobyname( "tcp" ); handle = pcap_open_live( iface, BUFSIZ, 1, 30000, errbuf ); pcap_lookupnet( iface, &net, &mask, errbuf ); pcap_compile( handle, &filter, filter_app, 0, net ); pcap_setfilter( handle, &filter ); printf( "SPort DPort Source Destination Length \n" ); /* packet = pcap_next( handle, &header ); */ pcap_loop(handle, 0, pcap_callback, NULL ); pcap_close( handle ); return 0; } void pcap_callback(u_char * useless, const struct pcap_pkthdr* pkthdr, const u_char * packet) { struct in_addr addr; struct packet_t * p; static char src[16], dst[16]; p = (struct packet_t *)packet; addr.s_addr = p->iph.ip_src.s_addr; strcpy( src, inet_ntoa( addr ) ); addr.s_addr = p->iph.ip_dst.s_addr; strcpy( dst, inet_ntoa( addr ) ); if( p->iph.ip_p == (u_char)(pe->p_proto) ) printf( "%5u %5u %18s%18s%18d\n", ntohs(p->tcph.th_sport), ntohs(p->tcph.th_dport), src, dst, pkthdr->len ); else printf( "----- ----- %18s%18s%18d\n", ntohs(p->tcph.th_sport), ntohs(p->tcph.th_dport), src, dst, pkthdr->len ); }