Я попытался прочитать в необработанном пакете с libpcap (1.4.0 на CentOS 6).
Однако по некоторым причинам rawPacket всегда имеет значение NULL после pcap_next_ex().
Однако pcap_next_ex() возвращает 1, хотя это может означать истечение времени ожидания (где тайм-аут задается путем?).
Во-первых, я думал, что строка фильтра, которую я передал в pcap_compile(), была неправильной. Но я попытался скопировать и вставить одну и ту же строку в tcpdump, она отлично работала - я вижу, что ожидаемые пакеты захватываются.
struct pcap_pkthdr *pHeader;
const u_char* rawPacket = NULL;
int rc = 0;
while (1) {
rc = pcap_next_ex(pDevice, &pHeader, &rawPacket);
if (-1 != rc && NULL != rawPacket) {
// process
struct ether_header* eptr = (struct ether_header *) rawPacket;
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));
}
}
}
Есть идеи?
Заранее спасибо.
Фактически, что говорит страница man pcap_next_ex()
pcap_next_ex() returns 1 if the packet was read without problems, 0 if
packets are being read from a live capture, and the timeout expired, -1
if an error occurred while reading the packet, and -2 if packets are
being read from a ''savefile'', and there are no more packets to read
from the savefile. If -1 is returned, pcap_geterr() or pcap_perror()
may be called with p as an argument to fetch or display the error text.
Мне нужно отредактировать его, чтобы удалить комментарий между "live capture" и "и истечением времени ожидания", потому что это означает, что pcap_next_ex()
возвращает:
pcap_open_live()
или, если вы использовали pcap_create()
и pcap_activate()
, pcap_set_timeout()
) истекли в ожидании пакета, и в этом случае не было прочитано ни одного пакета указатель будет установлен в NULL; Итак, что вы должны сделать после pcap_next_ex()
:
if (1 == rc) {
// process
struct ether_header* eptr = (struct ether_header *) rawPacket;
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 (0 == rc) {
// do nothing here - this isn't an error, but you have no packet
;
} else if (-1 == rc) {
// error
fprintf(stderr, "Error capturing or reading: %s\n", pcap_geterr(pDevice));
// quit trying to read or capture packets here
} else if (-2 == rc) {
// end of file if you're reading from a file
// this isn't an error, but there are no more packets to read
// so quit trying to read packets here
}