java抓包后对pcap文件解析示例
本文导语: 这是自己写的简单的解析pcap文件,方便读取pcap文件,大家参考使用吧 代码如下:InputStream is = DataParser.class.getClassLoader().getResourceAsStream("baidu_cdr.pcap"); Pcap pcap = PcapParser.unpack(is);is.close();byte[] t = pcap.getData().get(0).getContent();byte[] da...
这是自己写的简单的解析pcap文件,方便读取pcap文件,大家参考使用吧
InputStream is = DataParser.class.getClassLoader().getResourceAsStream("baidu_cdr.pcap");
Pcap pcap = PcapParser.unpack(is);
is.close();
byte[] t = pcap.getData().get(0).getContent();
byte[] data = Arrays.copyOfRange(t, 42, t.length);
PcapParser.java
package com.hylanda.pcap;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author zhouqisheng
*
*/
public class PcapParser {
public static Pcap unpack(InputStream is) throws IOException {
Pcap pcap = null;
byte[] buffer_4 = new byte[4];
byte[] buffer_2 = new byte[2];
pcap = new Pcap();
PcapHeader header = new PcapHeader();
int m = is.read(buffer_4);
if(m != 4){
return null;
}
reverseByteArray(buffer_4);
header.setMagic(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_2);
reverseByteArray(buffer_2);
header.setMagor_version(byteArrayToShort(buffer_2, 0));
m = is.read(buffer_2);
reverseByteArray(buffer_2);
header.setMinor_version(byteArrayToShort(buffer_2, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
header.setTimezone(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
header.setSigflags(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
header.setSnaplen(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
header.setLinktype(byteArrayToInt(buffer_4, 0));
pcap.setHeader(header);
List dataList = new ArrayList();
while (m > 0) {
PcapData data = new PcapData();
m = is.read(buffer_4);
if (m < 0) {
break;
}
reverseByteArray(buffer_4);
data.setTime_s(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
data.setTime_ms(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
data.setpLength(byteArrayToInt(buffer_4, 0));
m = is.read(buffer_4);
reverseByteArray(buffer_4);
data.setLength(byteArrayToInt(buffer_4, 0));
byte[] content = new byte[data.getpLength()];
m = is.read(content);
data.setContent(content);
dataList.add(data);
}
pcap.setData(dataList);
return pcap;
}
private static int byteArrayToInt(byte[] b, int offset) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i + offset] & 0x000000FF)