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

56 lines
1.6 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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;
}
// 编译过滤规则, 成功则设置过滤规则
char filter[] = "udp dst port 8001";
struct bpf_program program; // 过滤器程序结构体采用bpf伯克利包过滤器
if (pcap_compile(cap, &program, filter, 0, 0xffffff00) == 0)
{
pcap_setfilter(cap, &program);
}
// 循环捕获数据
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);
}