测试运行平台:CentOS 6.5发行版,内核版本3.11
3. 利用wireshark分析数据包
如果要使用wireshark分析数据包,则应将抓取到的数据按照pcap文件指定格式存储到文件中。
附:安装wireshark
sudo yum install wireshark
sudo yum install wireshak-gnome
(1)pcap文件头格式的结构体定义如下。
typedef struct pcap_file_hdr {
u_int32 magic;
u_short ver_major;
u_short ver_minor;
int32 timezone;
u_int32 sigfigs;
u_int32 snaplen;
u_int32 linktype;
}__attribute__((packed))PCAP_FILE_HDR;
(2)pcap每一条数据记录都应有数据包头,其定义如下。
typedef struct pcap_pkg_hdr {
u_int32 time_sec; //this represents the number of whole seconds of elapsed time.
u_int32 time_usec; //this is the rest of the elapsed time, represent it as a number of microseconds.
u_int32 caplen;
u_int32 len;
}__attribute__((packed)) PCAP_PKG_HDR;
在文件中写入数据包头后,即可将数据(buf)直接写入到文件中了。下面是一段生成cap文件的代码。
PCAP_FILE_HDR pcap_file_hdr = {0};
PCAP_PKG_HDR pcap_pkg_hdr = {0};
struct timeval ts;
File *pfile = NULL;
pfile = fopen(fname.pcap, "wb");
if(pfile == NULL){
fprintf(stdout, "no file will be saved.\n");
}else{
pcap_file_hdr->magic = 0xa1b2c3d4; //0xA1B2C3D4是pcap文件的固定文件识别头
pcap_file_hdr->ver_major = 0x02;
pcap_file_hdr->ver_minor = 0x04;
pcap_file_hdr->timezone = 0x00;
pcap_file_hdr->sigfigs = 0x00;
pcap_file_hdr->snaplen = 0xff;
pcap_file_hdr->linktype = 0x01;
fwrite(&pcap_file_hdr, sizeof(pcap_file_hdr), 1, pfile);
}
while(1){
n_rd = recvfrom(SOCKET_SRC, buf, BUFFER_MAX, 0, NULL, NULL); //returns the number of bytes received
if(n_rd < 46){
fprintf(stdout, "Incomplete header, packet corrupt\n");
continue;
}
printf("pkg size[%d] \n", n_rd);
if(pfile != NULL) {
gettimeofday(&ts, NULL);
pcap_pkg_hdr->time_usec = ts.tv_usec;
pcap_pkg_hdr->time_sec = ts.tv_sec;
pcap_pkg_hdr->caplen = sz;
pcap_pkg_hdr->len =sz;
fwrite(&pcap_pkg_hdr, sizeof(pcap_pkg_hdr), 1, pfile);
fwrite(buf, n_rd, 1, pfile);
}
/* termination control */
}
程序执行完成后,会发现在当前目录下生成了 fname.pcap文件,在shell中输入命令
wireshark fname.pcap
即可使用 wireshark 打开并观察数据包了。