我最近参与了不得不使用pf_ring / libpcap。我从来没有用libpcap或pf_ring开发,所以请原谅看似愚蠢的问题,因为网络编程对我来说是半新的...从广义上讲,我要做的是访问收到的数据包的if_index。我目前有一个简单的原始数据包嗅探器,使用" C"利用如下所示的pf_ring:
#include <pcap.h>
#include <pfring.h>
#include <string.h>
#include <stdlib.h>
#define MAXBYTES2CAPTURE 2048
void processRingPacket(const struct pfring_pkthdr* pkthdr, const u_char* packet, const u_char *arg)
{
int i=0, *counter = (int*)arg;
printf("Packet Count: %d ", ++(*counter));
printf("Received Packet Size: %d ", pkthdr->len);
printf("ifIndex: %d ", pkthdr->extended_hdr.if_index);
printf("Payload:\n");
for(i=0; i < pkthdr->len; i++)
{
if(isprint(packet[i]))
{
printf("%c ", packet[i]);
}
else
{
printf(". ");
}
if((i % 16 == 0) && (i != 0) || (i == pkthdr->len-1))
{
printf("\n");
}
}
return;
}
int main()
{
int count = 0;
char *device = "eth0";
printf("Opening Device: %s\n", device);
pfring* ring = pfring_open(device, MAXBYTES2CAPTURE, 0);
pfring_enable_ring(ring);
pfring_loop(ring, processRingPacket, (u_char*)&count, 1);
return 0;
}
查看pf_ring API中的pfring_pkthdr结构,我应该可以执行以下操作:
pkthdr->extended_hdr.if_index
但是,当我尝试打印索引时,它只打印0.我猜测if_index实际上并未设置,因为当我实际调用pf_ring函数来获取设备时,如果索引,我实际上会收到一个值指定的设备:
pfring_get_device_ifindex (pfring *ring, char *device_name, int *if_index)
问题是我正在尝试查看每个数据包的if_index,因此在回调函数&#34; processRingPacket&#34;没有办法一般性地指定设备。我在这里说一般,因为会有两个捕获数据包的接口。关于我的菜鸟错误可能有什么想法?
答案 0 :(得分:2)
我认为您需要将PF_RING_LONG_HEADER
作为标记传递给pfring_open()
。所以变成了pfring_open(device, MAXBYTES2CAPTURE, PF_RING_LONG_HEADER);
答案 1 :(得分:1)
如果在回调函数中没有设置pkthdr->extended_hdr.if_index
,您可以随时将其传递给arg
参数中的回调函数。
struct Dev {
int count;
int if_index;
};
...
char *device = "eth0";
struct Dev dev;
dev.count = 0;
dev.if_index = if_nametoindex(device); //from #include <net/in.h>
printf("Opening Device: %s\n", device);
pfring* ring = pfring_open(device, MAXBYTES2CAPTURE, 0);
pfring_enable_ring(ring);
pfring_loop(ring, processRingPacket, (u_char*)&dev, 1);
并在回调函数中恢复:
void processRingPacket(const struct pfring_pkthdr* pkthdr, const u_char* packet, const u_char *arg)
{
struct Dev *dev = (struct Dev*)arg;
int i=0, *counter = (int*)&dev->count;
//and use dev->if_index; whenever you need to.