socket

是的,你可以使用原始套接字(Raw Socket)来抓包,而不是使用libpcap。原始套接字允许你直接访问网络层(如IP层)或数据链路层(如以太网层)的数据包。通过这种方式,你可以手动构建和解析网络数据包,而不依赖于libpcap库。

 

使用原始套接字抓包

下面是一个使用原始套接字抓取以太网帧的基本示例,展示如何捕获并解析以太网头部、IP头部,以及判断协议类型(如TCP、UDP等),并提取和显示源/目的MAC地址、源/目的IP地址等信息。

 

c

复制代码

#include <stdio.h>

#include <string.h>

#include <sys/socket.h>

#include <arpa/inet.h>

#include <netinet/ip.h>

#include <netinet/tcp.h>

#include <netinet/udp.h>

#include <netinet/ether.h>

#include <unistd.h>

 

#define BUFFER_SIZE 65536

 

void process_packet(const unsigned char *buffer, int size) {

    struct ether_header *eth_hdr = (struct ether_header *)buffer;

    struct ip *ip_hdr = (struct ip *)(buffer + sizeof(struct ether_header));

    struct tcphdr *tcp_hdr;

    struct udphdr *udp_hdr;

    char src_ip[INET_ADDRSTRLEN], dst_ip[INET_ADDRSTRLEN];

    char src_mac[18], dst_mac[18];

 

    // 获取并打印源MAC地址和目的MAC地址

    snprintf(src_mac, sizeof(src_mac), "%02x:%02x:%02x:%02x:%02x:%02x",

             eth_hdr->ether_shost[0], eth_hdr->ether_shost[1],

             eth_hdr->ether_shost[2], eth_hdr->ether_shost[3],

             eth_hdr->ether_shost[4], eth_hdr->ether_shost[5]);

    snprintf(dst_m

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值