如何使用libpcap解析以太网数据包? [英] How can I parse an ethernet packet using libpcap?

查看:735
本文介绍了如何使用libpcap解析以太网数据包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中使用libpcap从pcap文件中读取数据包,例如:

I'm using libpcap in C++ for reading packets from pcap files, e.g.:

rc = pcap_next_ex((pcap_t*)handle, &header, (const unsigned char**)packet);

我想解析数据包头(没有有效载荷).

I would like to parse the packets header (without the payload).

例如,如何解析给定的数据包以提取其源IP和目标IP地址?

For example, how can I parse a given packet in order to extract its source and destintation ip addresses?

谢谢

推荐答案

检出libpcap的代码示例 http: //www.tcpdump.org/pcap.html

Checkout the code sample for libpcap http://www.tcpdump.org/pcap.html

got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);函数中,您有一个指针*packet指向数据包的开头.要解析以太网标头,您只需要使用相应的指针

In the got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); function you have a pointer *packet that points to the start of the packet. For parsing the ethernet headers you just need to use the corresponding pointer

ethernet = (struct sniff_ethernet*)(packet);

对于IP层

ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);

如果要解析其他协议,则只需定义自己的结构.如果要(或不希望)解析有效负载,则可以(或不)定义一个指向有效负载开始的指针.

If you want to parse other protocols, you just need to define your own structures. If you want (or do not want) to parse the payload then you can (or not) define a pointer to the start of the payload.

这篇关于如何使用libpcap解析以太网数据包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆