linux下使用libpcap库

Libpcap是一个开源C库,它提供了一个API,用于直接从Unix衍生操作系统的数据链路层捕获数据包。它被流行的数据包捕获应用程序(如tcpdump和snort)使用,使它们能够在几乎任何风格的Unix上运行。

下面是一个基于libpcap的简单数据包嗅探器应用程序的示例:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pcap.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <array>
#include <map>
#include <utility>

#pragma GCC diagnostic ignored "-Wunused-variable"


typedef std::array<u_char, 2048> Buf;
uint32_t nextExpectedSeq;
std::map<uint32_t, std::pair<uint32_t, Buf> > seq2UnprocessedMap;

const size_t buflen = 1024*1000;
u_char buf[buflen];
u_char* stream = buf;
u_char* recvp = buf;
uint32_t streamlen = 0;

void my_packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
void printHex(const u_char *payload, int payload_length);
size_t processStream(u_char *stream, size_t streamlen);

int main(int argc, char **argv)
{
   
    const char *filename = "p3p1.20220127.2.pcap";
    char error_buffer[PCAP_ERRBUF_SIZE];
    pcap_t *handle;
    /* End the loop after this many packets are captured */
    int total_packet_count = 20;
    u_char *my_arguments = NULL;
    struct bpf_program filter;
    char filter_exp[] = "dst port 60001";

    // handle = pcap_open_live(device, snapshot_length, 0, 10000, error_buffer);
    // Open the device for live capture, as opposed to reading a packet
    // capture file.
    if ((handle = pcap_open_offline(filename, error_buffer)) == NULL)
    {
   
        printf("pcap_open_offline(): %s\n", error_buffer);
        return 1;
    }
    if (pcap_compile(handle, &filter, filter_exp, 0, 0) == -1) {
   
        printf("Bad filter - %s\n", pcap_geterr(handle));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值