qfedu-network-advanced-level/day7/pcap3.c

48 lines
1.3 KiB
C
Raw Normal View History

2023-09-13 09:03:55 +08:00
// pcap_loop 循环接收数据
#include <pcap.h> // libpcap头文件
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/ether.h>
#include <netinet/ip.h>
#include <arpa/inet.h> // 网络地址转换函数,如inet_ntoa()->将网络地址转换成“.”点隔的字符串格式
#include <string.h>
#include <unistd.h>
void recv_data_handler(u_char *user_arg, const struct pcap_pkthdr *caphdr, const u_char *data);
int main(int argc, char const *argv[])
{
// 1. 获取可用的网络设备名称
char *dev = pcap_lookupdev(NULL); // NULL表示获取默认网络设备
if (dev != NULL)
{
printf("网络设备名称: %s\n", dev);
}
// 2. 打开网络设备, 开始捕获数据
char err_buf[PCAP_ERRBUF_SIZE] = "";
pcap_t *cap = pcap_open_live(dev, 128, 0, 0, err_buf);
if (cap == NULL)
{
printf("open pcap fail: %s\n", err_buf);
return -1;
}
// 循环捕获数据
pcap_loop(cap, -1, recv_data_handler, NULL);
// 关闭网卡设备
pcap_close(cap);
return 0;
}
void recv_data_handler(u_char *user_arg, const struct pcap_pkthdr *cap_hdr, const u_char *data)
{
if (cap_hdr->caplen > 0)
{
printf("数据包长度: %d, 实际长度: %d\n", cap_hdr->caplen, cap_hdr->len);
}
sleep(1);
}