Graphics Programs Reference
In-Depth Information
pcap_t *pcap_handle;
device = pcap_lookupdev(errbuf);
if(device == NULL)
pcap_fatal("pcap_lookupdev", errbuf);
printf("Sniffing on device %s\n", device);
pcap_handle = pcap_open_live(device, 4096, 1, 0, errbuf);
if(pcap_handle == NULL)
pcap_fatal("pcap_open_live", errbuf);
pcap_loop(pcap_handle, 3, caught_packet, NULL);
pcap_close(pcap_handle);
}
At the beginning of this program, the prototype for the callback func-
tion, called caught_packet() , is declared along with several decoding functions.
Everything else in main() is basically the same, except that the for loop has
been replaced with a single call to pcap_loop() . This function is passed the
pcap_handle , told to capture three packets, and pointed to the callback func-
tion, caught_packet() . The final argument is NULL , since we don't have any addi-
tional data to pass along to caught_packet() . Also, notice that the decode_tcp()
function returns a u_int. Since the TCP header length is variable, this function
returns the length of the TCP header.
void caught_packet(u_char *user_args, const struct pcap_pkthdr *cap_header, const u_char
*packet) {
int tcp_header_length, total_header_size, pkt_data_len;
u_char *pkt_data;
printf("==== Got a %d byte packet ====\n", cap_header->len);
decode_ethernet(packet);
decode_ip(packet+ETHER_HDR_LEN);
tcp_header_length = decode_tcp(packet+ETHER_HDR_LEN+sizeof(struct ip_hdr));
total_header_size = ETHER_HDR_LEN+sizeof(struct ip_hdr)+tcp_header_length;
pkt_data = (u_char *)packet + total_header_size; // pkt_data points to the data portion.
pkt_data_len = cap_header->len - total_header_size;
if(pkt_data_len > 0) {
printf("\t\t\t%u bytes of packet data\n", pkt_data_len);
dump(pkt_data, pkt_data_len);
} else
printf("\t\t\tNo Packet Data\n");
}
void pcap_fatal(const char *failed_in, const char *errbuf) {
printf("Fatal Error in %s: %s\n", failed_in, errbuf);
exit(1);
}
Search WWH ::




Custom Search