通过JPcap捕获网络TCP数据包,并将解析的信息写入execl文件中

以下代码主要实现功能:

1.利用JPcap捕获指定网卡的所有TCP数据包,并解析出"SRC_MAC","DST_MAC", "SRC_IP", "DST_IP", "GETInfo", "RefererInfo", "HostInfo"等信息。

2. 将这些信息不覆盖的写入到execl文件,并且将每天的数据信息记录在以年月日命名的execl工作表(sheet)中。

 

 

package execl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;




import jpcap.*;
import jpcap.packet.EthernetPacket;
import jpcap.packet.Packet;
import jpcap.packet.TCPPacket;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;



public class HttpMessageReceive implements PacketReceiver {
	
	public static File file = new File("G:" + File.separator + "Experiment"
			+ File.separator + "HTTP" + File.separator
			+ "DetailHTTPData.xls");
	public static File tempfile = new File("G:" + File.separator + "Experiment"
			+ File.separator + "HTTP" + File.separator + "temp.xls");
	public static String[] HttpInfoStr = {"0","0","0","0","0","0","0","0"};
	public static final String[] HTTPStart = {"GET","POST","OPTIONS"}; 	//HTTP协议有效信息开始的三个标志
	public static final String[] StrLabel = { "TimeOnLine", "SRC_MAC","DST_MAC", "SRC_IP", "DST_IP", "GETInfo", "RefererInfo", "HostInfo" };
		
	public static void main(String[] args) throws Exception {		
		NetworkInterface[] devices = JpcapCaptor.getDeviceList();
		if(args.length<1){
			System.out.println("usage: java Tcpdump <select a number from the following>");			
			for (int i = 0; i < devices.length; i++) {
				System.out.print(i+" :"+devices[i].name + "(" + devices[i].description+")");
				System.out.println("data link:"+devices[i].datalink_name + "("
						+ devices[i].datalink_description+")");
				System.out.print("MAC address:");
				for (byte b : devices[i].mac_address)
					System.out.print(Integer.toHexString(b&0xff) + ":");	
					System.out.println("");
				for (NetworkInterfaceAddress a : devices[i].addresses)
					System.out.println("address:"+a.address + " " + a.subnet + " "
							+ a.broadcast);
			}
		}else{
			JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[Integer.parseInt(args[0])], 2000, false, 20);
			jpcap.setFilter("tcp", true);    //设置过滤规则,只抓取tcps数据包
			jpcap.loopPacket(-1, new HttpMessageReceive());
		}
	}
	public void receivePacket(Packet packet) {			
			try {							
				String TimeOnLine = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
				HttpInfoStr[0] = TimeOnLine;    //时间戳			
				TCPPacket tcpPacket = (TCPPacket) packet;					
				EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink;				
				HttpInfoStr[1] = ethernetPacket.getSourceAddress();                	//SRC_MAC:
				HttpInfoStr[2] = ethernetPacket.getDestinationAddress();			//DST_MAC
				HttpInfoStr[3] = tcpPacket.src_ip.toString().substring(1);						//SRC_IP
				HttpInfoStr[4] = tcpPacket.dst_ip.toString().substring(1);						//DST_IP					
				String HTTPData = new String(tcpPacket.data,"utf-8");
				if(HTTPData.startsWith(HTTPStart[0])){  //GET方法访问					
					int GETInfoStart = 0;
					int GETInfoEnd = HTTPData.indexOf("\r\n",GETInfoStart);
					String GETInfo = HTTPData.substring(GETInfoStart, GETInfoEnd);
					HttpInfoStr[5] = GETInfo;

					int RefererInfoStart = HTTPData.indexOf("Referer");
					int RefererInfoEnd = HTTPData.indexOf("\r\n",RefererInfoStart);
					String RefererInfo = HTTPData.substring(RefererInfoStart, RefererInfoEnd);
					HttpInfoStr[6] = RefererInfo;
					
					int HostInfoStart = HTTPData.indexOf("Host");
					int HostInfoEnd = HTTPData.indexOf("\r\n",HostInfoStart);
					String HostInfo = HTTPData.substring(HostInfoStart, HostInfoEnd);
					HttpInfoStr[7] = HostInfo;				
				}else if(HTTPData.startsWith(HTTPStart[1])){ //POST方法访问
					//后续改进
					
				}	
				
				//将sbIPv4Data,GETInfo,HostInfo,RefererInfo信息写入文件DetailHTTPData.xls
				if(!"0".equals(HttpInfoStr[6])&& !"0".equals(HttpInfoStr[7])){   //当Host和Referer不为空时写入文件
					try {
						
						String sheetName = HttpInfoStr[0].substring(0, 8);
						int indexStrLabel = 0;
						int indexHttpInfo = 0;
						
						if(!file.exists()){
							WritableWorkbook wwb = Workbook.createWorkbook(file);
							WritableSheet ws = wwb.createSheet(sheetName, 0);
														
							while(indexStrLabel < StrLabel.length){
								Label label = new Label(indexStrLabel, 0, StrLabel[indexStrLabel]);
								ws.setColumnView(indexHttpInfo, HttpInfoStr[indexHttpInfo].length()+2);
								ws.addCell(label);
								indexStrLabel++;
							}
							while(indexHttpInfo < HttpInfoStr.length ){
								Label label = new Label(indexHttpInfo, 1, HttpInfoStr[indexHttpInfo]);
								ws.setColumnView(indexHttpInfo, HttpInfoStr[indexHttpInfo].length()+2);
								ws.addCell(label);
								indexHttpInfo++;
							}
							//写入Exel工作表
			                wwb.write();
			                //关闭Excel工作薄对象
			                wwb.close();	
			                System.out.println("=============================================");
						}else{
							
							Workbook rwb = Workbook.getWorkbook(file);
							WritableWorkbook wwb = Workbook.createWorkbook(tempfile, rwb);
							int sheetNum = rwb.getNumberOfSheets();	
							
							
							if(wwb.getSheet(sheetName) == null){
								WritableSheet ws = wwb.createSheet(sheetName, sheetNum);
								while(indexStrLabel < StrLabel.length){
									Label label = new Label(indexStrLabel, 0, StrLabel[indexStrLabel]);
									ws.setColumnView(indexHttpInfo, HttpInfoStr[indexHttpInfo].length()+2);
									ws.addCell(label);
									indexStrLabel++;
								}
								while(indexHttpInfo < HttpInfoStr.length ){
									Label label = new Label(indexHttpInfo, 1, HttpInfoStr[indexHttpInfo]);
									ws.setColumnView(indexHttpInfo, HttpInfoStr[indexHttpInfo].length()+2);
									ws.addCell(label);
									indexHttpInfo++;
								}
							}else{
								int CurrentSheetNumRows = rwb.getSheet(sheetName).getRows();
								WritableSheet ws = wwb.getSheet(sheetName);
								while(indexHttpInfo < HttpInfoStr.length ){
									Label label = new Label(indexHttpInfo, CurrentSheetNumRows, HttpInfoStr[indexHttpInfo]);
									ws.setColumnView(indexHttpInfo, HttpInfoStr[indexHttpInfo].length()+2);
									ws.addCell(label);
									indexHttpInfo++;
								}
							}				
							wwb.write();
							wwb.close();
							rwb.close();
							String filename = file.getPath();
							System.out.println("filename:" + filename);
							file.delete();
							tempfile.renameTo(file);
							System.out.println("tempfile:" + tempfile.getPath());
							System.out.println(tempfile.exists());
							System.out.println(file.exists());
							
						}
						
					} catch (WriteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}			
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
	}
}

 

 

 

 

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我了解到您想了解如何使用jpcap捕获HTTP数据包解析包头和包体。 首先,您需要下载并安装jpcap库,然后您可以使用以下代码片段来捕获HTTP数据包: ``` JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535, false, 20); captor.setFilter("tcp port 80", true); captor.loopPacket(-1, new HttpPacketReceiver()); ``` 其,devices是您的网络接口列表,index是您要使用的接口的索引。 然后,您需要创建一个实现了JpcapPacketReceiver接口的类HttpPacketReceiver,该类将处理捕获到的HTTP数据包。以下是一个简单的实现: ``` class HttpPacketReceiver implements JpcapPacketReceiver { @Override public void receivePacket(Packet packet) { // 只处理TCP数据包 if(packet instanceof TCPPacket) { TCPPacket tcp = (TCPPacket)packet; // 只处理80端口的HTTP数据包 if(tcp.dst_port == 80) { // 解析HTTP包头 String header = new String(tcp.data); // 解析HTTP包体 String body = new String(tcp.data); // 处理HTTP请求 if(header.startsWith("GET") || header.startsWith("POST")) { // TODO: 处理HTTP请求 } // 处理HTTP响应 else { // TODO: 处理HTTP响应 } } } } } ``` 在这个示例,我们只处理TCP数据包,并检查目标端口是否为80,因为HTTP协议默认使用80端口进行通信。然后,我们解析HTTP包头和包体,并根据请求类型或响应类型进行相应的处理。 希望这能帮助您开始使用jpcap捕获解析HTTP数据包

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值