既然我们能够捕获和过滤网络流量,我们希望把我们的知识与一个简单的“现实世界”应用程序一起使用。
在本课中,我们将从以前的课程中获取代码,并使用这些代码构建更有用的程序。当前程序的主要目的是显示如何解析和解释捕获的数据包的协议头。生成的应用程序UDPdump打印了我们网络上UDP流量的摘要。
我们选择解析和显示UDP协议,因为它比其他协议(如TCP)更易于访问,因此是一个很好的初始示例。我们来看看代码:
#include "pcap.h"
/* 4 bytes IP address */
typedef struct ip_address{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
/* IPv4 header */
typedef struct ip_header{
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
}ip_header;
/* UDP header*/
typedef struct udp_header{
u_short sport; // Source port
u_short dport; // Destination port
u_short len; // Datagram length
u_short crc; // Checksum
}udp_header;
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP