2 * Copyright (C) 2009, 2010 Daniel Borkmann <daniel@netsniff-ng.org> and
3 * Emmanuel Roullit <emmanuel@netsniff-ng.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
28 #include <sys/types.h>
30 #include <linux/if_packet.h>
31 #include <linux/if_ether.h>
37 int pcap_has_packets(int fd
)
40 struct pcap_sf_pkthdr sf_hdr
;
43 warn("Can't open file.\n");
47 if ((pos
= lseek(fd
, (off_t
) 0, SEEK_CUR
)) < 0) {
48 err("Cannot seek offset of pcap file");
53 /* Test pcap header */
54 if (read(fd
, (char *)&sf_hdr
, sizeof(sf_hdr
)) != sizeof(sf_hdr
)) {
59 if (lseek(fd
, pos
+ sf_hdr
.len
, SEEK_SET
) < 0) {
63 /* Rewind the offset */
64 if (lseek(fd
, pos
, SEEK_SET
) < 0) {
65 err("Cannot rewind pcap file");
73 int pcap_validate_header(int fd
)
75 struct pcap_file_header hdr
;
78 warn("Can't open file.\n");
82 if (read(fd
, (char *)&hdr
, sizeof(hdr
)) != sizeof(hdr
)) {
83 err("Error reading dump file");
87 if (hdr
.magic
!= TCPDUMP_MAGIC
88 || hdr
.version_major
!= PCAP_VERSION_MAJOR
89 || hdr
.version_minor
!= PCAP_VERSION_MINOR
90 || hdr
.linktype
!= LINKTYPE_EN10MB
) {
92 err("This file is certainly not a valid pcap");
99 size_t pcap_fetch_next_packet(int fd
, struct tpacket_hdr
* tp_h
,
102 struct pcap_sf_pkthdr sf_hdr
;
106 if (tp_h
== NULL
|| sp
== NULL
) {
108 err("Can't access packet header");
112 if (read(fd
, (char *)&sf_hdr
, sizeof(sf_hdr
)) != sizeof(sf_hdr
)) {
116 tp_h
->tp_sec
= sf_hdr
.ts
.tv_sec
;
117 tp_h
->tp_usec
= sf_hdr
.ts
.tv_usec
;
118 tp_h
->tp_snaplen
= sf_hdr
.caplen
;
119 tp_h
->tp_len
= sf_hdr
.len
;
121 if (read(fd
, (char *)sp
, sf_hdr
.len
) != sf_hdr
.len
) {