【libpcap】获取报文pcap的ns级别的时间戳

1.安装libpcap

首先,下载最新的 libpcap 源代码。你可以从 tcpdump.org 获取最新版本

1 解压下载的libpcap
tar -zxvf libpcap-version.tar.gz
2 进入解压目录进行安装
cd libpcap-version
./configure
make
sudo make install

2 解析报文时间戳

#include 
#include 

int main() {
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;

    // 替换为你的网络接口名称,例如 "eth0"
    char *dev = "eth3";

    // 创建 pcap 句柄
    handle = pcap_create(dev, errbuf);
    if (handle == NULL) {
        fprintf(stderr, "无法创建 pcap 句柄: %s\n", errbuf);
        return 1;
    }

    // 设置纳秒级时间戳精度
    if (pcap_set_tstamp_precision(handle, PCAP_TSTAMP_PRECISION_NANO) != 0) {
        fprintf(stderr, "设置纳秒级时间戳精度失败: %s\n", pcap_geterr(handle));
        // 也可以选择在这里退出,如果纳秒级别时间戳是必需的
    }

    // 激活 pcap 句柄
    if (pcap_activate(handle) != 0) {
        fprintf(stderr, "激活 pcap 句柄失败: %s\n", pcap_geterr(handle));
        pcap_close(handle);
        return 1;
    }

    // 检查实际的时间戳精度
    int tstamp_precision = pcap_get_tstamp_precision(handle);

    struct pcap_pkthdr *header;
    const u_char *packet;

    // 捕获循环
    while (pcap_next_ex(handle, &header, &packet) >= 0) {
        // 根据时间戳精度打印时间
        if (tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
            printf("Timestamp: %ld seconds, %ld nanoseconds\n",
                   header->ts.tv_sec, header->ts.tv_usec);
        } else {
            printf("Timestamp: %ld seconds, %ld microseconds\n",
                   header->ts.tv_sec, header->ts.tv_usec);
        }
    }

    pcap_close(handle);
    return 0;
}

编译:

gcc -o packet_capture packet.c -I/custom/path/include -L/custom/path/lib -lpcap

-I/custom/path/include 告诉编译器在 /custom/path/include 目录中查找头文件。通常这是安装 libpcap 头文件的地方。
-L/custom/path/lib 告诉编译器在链接阶段查找库文件的 /custom/path/lib 目录。这是 .so 文件通常所在的位置。
-lpcap 指示编译器链接 libpcap 库
运行:

sudo ./packet_capture

效果:
【libpcap】获取报文pcap的ns级别的时间戳_第1张图片

你可能感兴趣的:(网络,算法,linux,libpcap)