学习libpcap库,写例子代码--主文件

本文将展示如何利用libpcap库和C++语言实现网络数据包捕获功能,包括设置本地主机环境、查找网络设备、打开连接并配置过滤器等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <locale>
#include <libintl.h>
#include <iostream>
#include <string>
#include <pcap.h>
#define _(data) gettext(data)
#include "ether.hpp"




int main(int argc, char* argv[])
{
  std::locale host_locale("");
  textdomain("pcap");
  bindtextdomain("libpcap", "language");

  char error_buf[PCAP_ERRBUF_SIZE];
  char* device_name = pcap_lookupdev(error_buf);
  if (device_name == NULL)
    {
      std::cout<<error_buf<<std::endl;
      return -1;
    }
  std::cout<<device_name<<std::endl;

  /*
  bpf_u_int32 net;
  bpf_u_int32 mask;
  if (pcap_lookupnet(device_name, &net, &mask, error_buf) == -1)
    {
      std::cout<<error_buf<<std::endl;
      return -1;
    }
  */
  pcap_t* session = pcap_open_live(device_name, BUFSIZ, 1, -1, error_buf);
  if (session == NULL)
    {
      std::cout<<error_buf<<std::endl;
      return -1;
    }
  /*
  bpf_program fp;
  const char* filter = "tcp";
  if (pcap_compile(session, &fp, filter, 1, mask) < 0)
    {
      std::cout<<pcap_geterr(session)<<std::endl;
      pcap_close(session);
      return -1;
    }
  if (pcap_setfilter(session, &fp) < 0)
    {
      std::cout<<pcap_geterr(session)<<std::endl;
      pcap_close(session);
      return -1;
      }*/

  if (pcap_loop(session, -1, del_ether, NULL) == -1)
    {
      std::cout<<pcap_geterr(session)<<std::endl;
      pcap_close(session);
      return -1;
    }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值