libpcap--01

1. 抓包 pcap_next

/* libpcap使用案例
 * main.cpp
 * Created on: Jun 5,2021
 * Author :lei
 */
#include <pcap.h>
#include <string.h>
#include <iostream>
#define PCAP_ERRBUF_SIZE 256
using namespace std;
int test01(){
    char *dev, errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;
    /* 获取第一个可用的网口: */
    dev = pcap_lookupdev(errbuf);
    if(dev ==NULL){
        fprintf(stderr,"Couldn't find default device: %sn",errbuf);
        return(2);
    }
    printf("Device:%s\n",dev);

    /* 打开监听的设备 */
    handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
    if(handle ==NULL){
        fprintf(stderr,"Couldn't find default device: %sn",errbuf);
        return(2);
    }

    /* 设置过滤条件 */
    bpf_u_int32 net;
    bpf_u_int32 mask;
    if(pcap_lookupnet(dev, &net, &mask, errbuf)==-1){
        fprintf(stderr,"Can't get netmask for device %sn",errbuf);
        net = 0;
        mask = 0;
        return(2);
    }

    /* 编译过滤条件 */
    struct bpf_program fp;
    char filter_exp[] = "ip";
    if( pcap_compile(handle, &fp, filter_exp , 0, net)==-1){
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
	    return(2);
    }

    /* 设置过滤条件 */
    if (pcap_setfilter(handle, &fp)==-1){
	    fprintf(stderr, "Couldn't install filter %s: %sn", filter_exp, pcap_geterr(handle));
	    return(2);
    }

    /* 捕捉包 */
    const u_char *packet;
    pcap_pkthdr header;
    if((packet = pcap_next(handle, &header))==NULL){
        printf("抓包出错\n");
        return 2;
    }
    printf("jacked a packet with length of [%d]\n", header.len);
    printf("packet:%s\n",packet);

    /* 输出数据包 */
    if (header.len != header.caplen){
        printf("Warning! Capture size different than packet size: %d bytes\n", header.len);
    }
    for (u_int i=0; (i < header.caplen ) ; i++)
        {
            // Start printing on the next after every 16 octets
            if ( (i % 16) == 0) printf("\n");
 
            // Print each octet as hex (x), make sure there is always two characters (.2).
            printf("%.2x ", packet[i]);
        }
    printf("\n");

    /*关闭 session */
    pcap_close(handle);

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值