为了从接收到的IP数据包中提取时间戳、协议、源IP、目的IP、源端口、目的端口、源MAC、目的MAC和报文长度,我们可以创建一个结构体来存储这些信息。然后,我们可以在解析数据包时填充这个结构体。以下是如何实现的步骤:
1. 定义结构体
首先,定义一个结构体 PacketInfo 来存储这些信息。
c
Copy code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <unistd.h>
#include <time.h>
struct PacketInfo {
char timestamp[64]; // 时间戳
char protocol[16]; // 协议类型 (如TCP, UDP, ICMP)
char src_ip[INET_ADDRSTRLEN]; // 源IP地址
char dest_ip[INET_ADDRSTRLEN];// 目的IP地址
unsigned short src_port; // 源端口
unsigned short