是的,你可以使用原始套接字(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