libpcap 中的数据包向量
我正在使用 c / c++ 中的 libpcap,并且在向量中插入指针时遇到问题。 这是我的代码:
typedef vector <u_char *>vPack;
...
vPack vect;
...
if (pcap_dispatch (p, 0, &mycallback, (u_char *) &vect) < 0){
cout << "Error" << endl;
pcap_perror (p, prestr);
}
....
void mycallback (u_char * args, const struct pcap_pkthdr *pkthdr, const u_char * packet){
u_char *pk;
pk = (u_char *)packet;
vPack *vec = (vPack *) args;
vec[0].push_back(pk);
}
问题是元素被插入到相同的内存位置,并且向量始终包含相同的元素。 有什么建议吗?
PD:对不起我的英语。
I'm working with libpcap in c / c + + and I have a problem when inserting pointers in a vector.
This is my code:
typedef vector <u_char *>vPack;
...
vPack vect;
...
if (pcap_dispatch (p, 0, &mycallback, (u_char *) &vect) < 0){
cout << "Error" << endl;
pcap_perror (p, prestr);
}
....
void mycallback (u_char * args, const struct pcap_pkthdr *pkthdr, const u_char * packet){
u_char *pk;
pk = (u_char *)packet;
vPack *vec = (vPack *) args;
vec[0].push_back(pk);
}
The problem is that the elements are inserted in the same memory location, and the vector always contains the same element.
Any suggestions?
PD: sorry for my english.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在
mycallback
中,参数packet
是一个const u_char
- 缓冲区。该指针指向 libpcap 内部数据缓冲区,该缓冲区可重复用于与您的过滤器匹配的每个数据包(并且调用您的回调)。您必须创建自己的缓冲区并将数据包数据复制到其中。例如:
In
mycallback
the argumentpacket
is aconst u_char
- buffer. This pointer points to an libpcap-internal data buffer which is reused for every packet which has matched your filter (and your callback is called). You have to create your own buffer and copy the packet-data into it.For example:
您必须将数据复制到新分配的内存中:
但是,需要考虑一些重要问题:
向量
内的时间。您确实需要一个类来存储数据及其长度,然后存储这些对象的向量
。You have to copy the data to a freshly allocated piece of memory:
However there are important issues to consider:
vector
you must iterate through each element and explicitlydelete
it, in order to recover memory.vector
. You really need a class that stores both the data and its length and then store avector
of these objects instead.延长卡雷克的尝试!
extending Karrek's attempt!
真是一团糟!让我们使用 文档 做出一个 C++ 答案:
这里唯一值得注意的一点是我们通过
user
参数传递一个指向v
的指针,因此我们必须在两端进行一些类型不安全的转换。不过,这正是使用 C 回调函数的标志。What a mess! Let's make a C++ answer, using the documentation:
The only noteworth point here is that we pass a pointer to
v
through theuser
argument, so we have to do some type-unsafe casting on both ends. That's just the hallmark of using a C callback function, though.