libpcap pcap_loop捕获包数据

pcap_loop, pcap_dispatch - process packets from a live capture or savefile
处理抓取的数据包

函数原型
#include <pcap/pcap.h>
typedef void (*pcap_handler)(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes);
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user);

pcap_loop()处理捕获给定的cnt个数据包,如果给定的参数cnt是-1或0,则表示将无限的捕获数据包。
回调函数pcap_handler处理具体的数据包,
回调函数有三个参数:
u_char *user参数是pcap_loop通过user(第三个参数)传递给pcap_handler的;
const struct pcap_pkthdr *h参数表示包的时间戳和长度;
const u_char *bytes参数表示h中长度的数据。

pcap_loop() processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop(3PCAP) is called, or an error occurs. It does not retur

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你的问题是如何获取已经绑定的网卡列表并通过 Libpcap捕获网络数据端口进行设定,对吧?那我来回答一下。 首先,可以使用 Libpcap 提供的 pcap_findalldevs_ex() 函数来获取已经绑定的网卡列表。这个函数会返回一个指向 pcap_if 结构体的链表,其中每个结构体含了一个已经绑定的网卡的全部信息,比如网卡的名称、描述和 IP 地址等。 获取网卡列表的示例代码如下: ```c pcap_if_t* alldevs; char errbuf[PCAP_ERRBUF_SIZE]; if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) { fprintf(stderr, "Error in pcap_findalldevs_ex: %s\n", errbuf); exit(1); } // 遍历链表,输出每个网卡的信息 for (pcap_if_t* dev = alldevs; dev != NULL; dev = dev->next) { printf("Name: %s\n", dev->name); printf("Description: %s\n", dev->description); for (pcap_addr_t* addr = dev->addresses; addr != NULL; addr = addr->next) { printf("IP address: %s\n", addr->addr->sa_data); } } ``` 上面的代码会输出每个网卡的名称、描述和 IP 地址。 接下来,可以使用 Libpcap 提供的 pcap_open_live() 函数来打开一个网络接口,并设定监听的网络端口。这个函数需要传入网卡的名称、要捕获数据的最大长度、是否开启混杂模式等参数。 打开网络接口的示例代码如下: ```c char* devname = "eth0"; // 网卡的名称 int snaplen = 65535; // 最大捕获长度 int promisc = 1; // 是否开启混杂模式 int to_ms = 1000; // 超时时间,单位是毫秒 char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* handle; handle = pcap_open_live(devname, snaplen, promisc, to_ms, errbuf); if (handle == NULL) { fprintf(stderr, "Error in pcap_open_live: %s\n", errbuf); exit(1); } // 这里可以使用 pcap_loop() 函数来循环捕获数据 ``` 上面的代码会打开一个名为 "eth0" 的网卡,并开启混杂模式来捕获所有经过该网卡的数据。 希望这个回答能够解决你的问题!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值