简单的网络数据包分析小程序

这篇博客介绍了一个小型程序,它利用pcap库来抓取和分析网络数据包,涉及MAC、IP和TCP层的头部信息。通过理解这些数据包的结构,程序能够深入洞察网络通信细节。

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

对MAC、IP、TCP等的数据包进行抓取分析其结构,使用了pcap库

1.mac.h

#include <string>
#include <iostream>
#include <cstdio>

class PMacHeader
{
private:
    const unsigned char *m;
    std::string dst, src, type, tpname;
public:
    PMacHeader(const unsigned char *p = 0){m = p;}
    ~PMacHeader(){m = 0;}
    void ResetPt(const unsigned char * p){m = p;}
    unsigned short GetProtocol();
    std::string& GetDstStr();
    std::string& GetSrcStr();
};

2.mac.cpp

#include "stdafx.h"
#include "mac.h"

unsigned short PMacHeader::GetProtocol()
{
    unsigned short thetype;
    thetype = (unsigned short)m[12] << 8;
    thetype += (unsigned short)m[12+1];
    return thetype;
}
std::string& PMacHeader::GetDstStr()
{
    char dstBuf[6*3+1];
    std::sprintf(dstBuf, "%.2x %.2x %.2x %.2x %.2x %.2x ", m[0], m[1], m[2], m[3], m[4], m[5]);
    dst = dstBuf;
    return dst;
}
std::string& PMacHeader::GetSrcStr()
{
    char srcBuf[6*3+1];
    std::sprintf(srcBuf,"%.2x %.2x %.2x %.2x %.2x %.2x ", m[6], m[7], m[8], m[9], m[10], m[11]);
    src = srcBuf;
    return src;
}
3.ip.h

#include <string>
#include <iostream>
#include <cstdio>

class PIpHeader
{
private:
    const unsigned char *p;
    std::string src, dst;
public:
    PIpHeader(const unsigned char *pt = 0):p(pt){}
    ~PIpHeader(){p = 0;}
    void Reset(const unsigned char *pt){ p = pt;}
    short GetVesion();//取IP的版本
    short GetHeaderLen();//取IP报头的长度 (1单位/4字节)
    short GetServer();//服务
    unsigned short GetTotalLen();//总长度
    unsigned short GetID();//标识
    short GetFlag();
    short GetEx();//偏移量
    short GetTTL();
    unsigned short GetProtocol();
    unsigned short GetCheck();//校验码
    std
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值