网络嗅探器的设计(2)
參考https://blog.csdn.net/qq_34838643/article/details/78891127
標題
使用java進行實現網絡嗅探器。
實驗環境
Win10+Eclipse+JDK1.8+Winpcap+Jpcap
Jpcap
Jpcap實際上并非一個真正去實現對數據鏈路層的控制,而是一個中間件,JPCAP調用wincap/libpcap,而給JAVA語言提供一個公共的接口,從而實現了平臺無關性。Java的.net包中,給出了傳輸層協議 TCP和UDP有關的API,用戶只能操作傳輸層數據,要想直接操作網絡層{比如自己寫傳輸層數據報(自己寫傳輸層包頭),或者自己寫好IP數據包向網絡中發}則是無能為力的。 而JPCAP擴展包彌補了這一點,使我們可以支持從網卡中接收IP數據包,或者向網卡中發送IP數據包。
框架設計
MVC
詳情請見:https://blog.csdn.net/qq_37865996/article/details/84311020
Jpcap的安裝和使用
下載:https://download.csdn.net/download/qq_37865996/10797446
解壓后,在已配置好java的環境和IDE后,將壓縮包中的jpcap.dll粘貼到jre的bin文件夾中去。
將jpcap.jar作為庫文件
Winpcap
在windows中進行抓包這是必不可少的。
https://www.winpcap.org/archive/
功能設置
1.作為Sniffer,即實現嗅探功能,抓包并分析;
2.選定網卡;
3.偵聽所有進出本主機的數據包,解析顯示數據包( ICMP 、 IP 、 TCP 、 UDP 等)各個字段及數據內容?
4.指定功能:
偵聽來源于指定 IP 地址的數據包,偵聽指定目的 IP 地址的數據包 ;
獲取數據包的詳細信息,首部的各字段,包括源IP,目的IP,源端口,目的端口,源MAC,目的MAC等,將數據內容通過gbk方式解碼;
偵聽指定協議的數據包;
偵聽含有指定數據的數據報包 ;
保存選中的包到本地。
使用流程
(1)啟動程序,展示用戶界面?
(2)獲取當前網卡列表,用戶指定要操作的網卡?
(3)獲取當前過濾規則,可通過協議,源IP,目的IP,關鍵字進行過濾,也可為空?
(4)展示數據包基本信息?
(5)根據用戶點擊的內容,對該包進行解析,顯示詳細內容
?
代碼
cControl
NetworkCard.java網卡類
package cControl; import jpcap.*;public class NetworkCard {String[] devices;public static NetworkInterface[] getDevices() {NetworkInterface[] devices = JpcapCaptor.getDeviceList();return devices;} }PacketAnanlyze.java分析類
package cControl;import java.io.UnsupportedEncodingException; import java.util.HashMap; import jpcap.packet.*;public class PacketAnalyze {static Packet packet;static HashMap<String,String> att,att1;public PacketAnalyze(Packet packet){this.packet = packet; }public static HashMap<String,String> packetClass(){att1 = new HashMap<String,String>();if(packet.getClass().equals(ICMPPacket.class)){att1 = ICMPanalyze();}else if(packet.getClass().equals(TCPPacket.class)){att1 = TCPanalyze();}else if(packet.getClass().equals(UDPPacket.class)){att1 = UDPanalyze();}return att;}public static HashMap<String,String> IPanalyze(){att = new HashMap<String,String>();if(packet instanceof IPPacket){IPPacket ippacket = (IPPacket) packet;att.put("協議", new String("IP"));att.put("源IP", ippacket.src_ip.toString().substring(1, ippacket.src_ip.toString().length()));att.put("目的IP", ippacket.dst_ip.toString().substring(1, ippacket.dst_ip.toString().length()));att.put("TTL", String.valueOf(ippacket.hop_limit));att.put("頭長度", String.valueOf(ippacket.header.length));att.put("是否有其他切片", String.valueOf(ippacket.more_frag));}return att;}public static HashMap<String,String> ICMPanalyze(){att = new HashMap<String,String>();ICMPPacket icmppacket = (ICMPPacket) packet;att.put("協議", new String("ICMP"));att.put("源IP", icmppacket.src_ip.toString().substring(1, icmppacket.src_ip.toString().length()));att.put("目的IP", icmppacket.dst_ip.toString().substring(1, icmppacket.dst_ip.toString().length()));return att;}public static HashMap<String,String> TCPanalyze(){att = new HashMap<String,String>();TCPPacket tcppacket = (TCPPacket) packet;EthernetPacket ethernetPacket=(EthernetPacket)packet.datalink;att.put("協議", new String("TCP"));att.put("源IP", tcppacket.src_ip.toString().substring(1, tcppacket.src_ip.toString().length()));att.put("源端口", String.valueOf(tcppacket.src_port));att.put("目的IP", tcppacket.dst_ip.toString().substring(1, tcppacket.dst_ip.toString().length()));att.put("目的端口", String.valueOf(tcppacket.dst_port));att.put("源MAC", ethernetPacket.getSourceAddress());att.put("目的MAC", ethernetPacket.getDestinationAddress());try {att.put("數據", new String(tcppacket.data,"gbk"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}return att;}public static HashMap<String,String> UDPanalyze(){att = new HashMap<String,String>();UDPPacket udpppacket = (UDPPacket) packet;EthernetPacket ethernetPacket=(EthernetPacket)packet.datalink;att.put("協議", new String("UDP"));att.put("源IP", udpppacket.src_ip.toString().substring(1, udpppacket.src_ip.toString().length()));att.put("源端口", String.valueOf(udpppacket.src_port));att.put("目的IP", udpppacket.dst_ip.toString().substring(1, udpppacket.dst_ip.toString().length()));att.put("目的端口", String.valueOf(udpppacket.dst_port));att.put("源MAC", ethernetPacket.getSourceAddress());att.put("目的MAC", ethernetPacket.getDestinationAddress());try {att.put("數據", new String(udpppacket.data,"gbk"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}return att;} }PacketCaputure.java抓包類?
package cControl;import java.io.IOException; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.table.*; import jpcap.*; import jpcap.packet.*;/*抓包*/ public class PacketCapture implements Runnable {NetworkInterface device;static DefaultTableModel tablemodel;static String FilterMess = "";static ArrayList<Packet> packetlist = new ArrayList<Packet>();public PacketCapture() {}public void setDevice(NetworkInterface device){this.device = device;}public void setTable(DefaultTableModel tablemodel){this.tablemodel = tablemodel;}public void setFilter(String FilterMess){this.FilterMess = FilterMess;}public void clearpackets(){packetlist.clear();}@Overridepublic void run() {// TODO Auto-generated method stubPacket packet;try {JpcapCaptor captor = JpcapCaptor.openDevice(device, 65535,true, 20);//System.out.println(device.name);while(true){long startTime = System.currentTimeMillis();while (startTime + 600 >= System.currentTimeMillis()) {//captor.setFilter(FilterMess, true);packet = captor.getPacket();// 設置過濾器if(packet!=null&&TestFilter(packet)){//System.out.println(packet);packetlist.add(packet);showTable(packet);}}Thread.sleep(2000);}} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} }//將抓到包的信息添加到列表public static void showTable(Packet packet){String[] rowData = getObj(packet);tablemodel.addRow(rowData);}//其他類通過此方法獲取Packet的列表public static ArrayList<Packet> getpacketlist(){return packetlist;}//設置過濾規則public static boolean TestFilter(Packet packet){if(FilterMess.contains("sip")){String sip = FilterMess.substring(4, FilterMess.length());if(new PacketAnalyze(packet).packetClass().get("源IP").equals(sip)){return true;}}else if(FilterMess.contains("dip")){String dip = FilterMess.substring(4, FilterMess.length());if(new PacketAnalyze(packet).packetClass().get("目的IP").equals(dip)){return true;}}else if(FilterMess.contains("ICMP")){if(new PacketAnalyze(packet).packetClass().get("協議").equals("ICMP")){return true;}}else if(FilterMess.contains("UDP")){if(new PacketAnalyze(packet).packetClass().get("協議").equals("UDP")){return true;}}else if(FilterMess.contains("TCP")){if(new PacketAnalyze(packet).packetClass().get("協議").equals("TCP")){return true;}}else if(FilterMess.contains("keyword")){String keyword = FilterMess.substring(8, FilterMess.length());if(new PacketAnalyze(packet).packetClass().get("數據").contains(keyword)){return true;}}else if(FilterMess.equals("")){return true;}return false;}//將抓的包的基本信息顯示在列表上,返回信息的String[]形式public static String[] getObj(Packet packet){String[] data = new String[6];if (packet != null&&new PacketAnalyze(packet).packetClass().size()>=3) {Date d = new Date();DateFormat df = new SimpleDateFormat("HH:mm:ss");data[0]=df.format(d);data[1]=new PacketAnalyze(packet).packetClass().get("源IP");data[2]=new PacketAnalyze(packet).packetClass().get("目的IP");data[3]=new PacketAnalyze(packet).packetClass().get("協議");data[4]=String.valueOf(packet.len);}return data;} }main
Main.java
package main;import javax.swing.JMenuItem;import jpcap.NetworkInterface; import cControl.NetworkCard; import show.MyInterface;public class Main {public static void main(String[] args) {// TODO Auto-generated method stubnew MyInterface();}}view
MyInterface.java界面類
package show;import java.awt.*; import java.awt.event.*; import java.io.FileOutputStream; import java.util.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import jpcap.NetworkInterface; import jpcap.packet.Packet; import cControl.PacketCapture; import cControl.NetworkCard; import cControl.PacketAnalyze;public class MyInterface extends JFrame{JMenuBar menubar; //菜單條JMenu menuFile1,menuFile2; //菜單JMenuItem[] item; //菜單項JMenuItem pro1,pro2,pro3;JTextField searchText;JButton sipButton,dipButton,searchButton;JPanel panel; JScrollPane scrollPane; JTable table; final String[] head = new String[] {"時間","源IP", "目的IP", "協議", "長度"};NetworkInterface[] devices;Object[][] datalist = {};DefaultTableModel tableModel;PacketCapture allpackets;public MyInterface(){allpackets = new PacketCapture();this.setTitle("MySniffer");this.setBounds(650, 150, 1200, 1000);menubar = new JMenuBar();//根據網卡進行過濾menuFile1 = new JMenu(" 網卡 ");NetworkInterface[] devices = new NetworkCard().getDevices();item = new JMenuItem[devices.length];for (int i = 0; i < devices.length; i++) {item[i] = new JMenuItem(i + ": " + devices[i].name + "("+ devices[i].description + ")");menuFile1.add(item[i]);item[i].addActionListener(new CardActionListener(devices[i]));}//根據協議進行過濾menuFile2 = new JMenu(" 協議 ");pro1 = new JMenuItem("ICMP");pro2 = new JMenuItem("TCP");pro3 = new JMenuItem("UDP");pro1.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e3) { allpackets.setFilter("ICMP");allpackets.clearpackets();while(tableModel.getRowCount()>0){tableModel.removeRow(tableModel.getRowCount()-1);}} }); pro2.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e3) { allpackets.setFilter("TCP");allpackets.clearpackets();while(tableModel.getRowCount()>0){tableModel.removeRow(tableModel.getRowCount()-1);}} });pro3.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e3) { allpackets.setFilter("UDP");allpackets.clearpackets();while(tableModel.getRowCount()>0){tableModel.removeRow(tableModel.getRowCount()-1);}} }); menuFile2.add(pro1);menuFile2.add(pro2);menuFile2.add(pro3);//根據源IP進行過濾sipButton = new JButton(" 源IP ");sipButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { String fsip = JOptionPane.showInputDialog("請輸入源IP,以篩選數據包:"); allpackets.setFilter("sip "+fsip);allpackets.clearpackets();while(tableModel.getRowCount()>0){tableModel.removeRow(tableModel.getRowCount()-1);}} });//根據目的IP進行過濾dipButton = new JButton(" 目的IP ");dipButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { String fdip = JOptionPane.showInputDialog("請輸入目的IP,以篩選數據包:"); allpackets.setFilter("dip "+fdip);allpackets.clearpackets();while(tableModel.getRowCount()>0){tableModel.removeRow(tableModel.getRowCount()-1);}} });//根據關鍵字進行過濾searchButton = new JButton(" 查找 ");searchButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { String fkeyword = JOptionPane.showInputDialog("請輸入數據關鍵字,以篩選數據包:"); allpackets.setFilter("keyword "+fkeyword);allpackets.clearpackets();while(tableModel.getRowCount()>0){tableModel.removeRow(tableModel.getRowCount()-1);}} });//將菜單添加到菜單條上menubar.add(menuFile1); menubar.add(menuFile2);menubar.add(sipButton);menubar.add(dipButton);menubar.add(searchButton);setJMenuBar(menubar);tableModel = new DefaultTableModel(datalist, head);table = new JTable(tableModel){public boolean isCellEditable(int row, int column){return false;}};allpackets.setTable(tableModel); table.setPreferredScrollableViewportSize(new Dimension(500, 60));// 設置表格的大小 table.setRowHeight(30);// 設置每行的高度為20 table.setRowMargin(5);// 設置相鄰兩行單元格的距離 table.setRowSelectionAllowed(true);// 設置可否被選擇.默認為false table.setSelectionBackground(Color.cyan);// 設置所選擇行的背景色 table.setSelectionForeground(Color.red);// 設置所選擇行的前景色 table.setShowGrid(true);// 是否顯示網格線 table.doLayout(); scrollPane = new JScrollPane(table); panel = new JPanel(new GridLayout(0, 1)); panel.setPreferredSize(new Dimension(600, 300)); panel.setBackground(Color.black); panel.add(scrollPane); setContentPane(panel); pack(); table.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent ev){if(ev.getClickCount() == 2){int row = table.getSelectedRow();JFrame frame = new JFrame("詳細信息");JPanel panel = new JPanel();final JTextArea info = new JTextArea(23, 42);info.setEditable(false);info.setLineWrap(true);info.setWrapStyleWord(true);frame.add(panel);panel.add(new JScrollPane(info));JButton save = new JButton("保存到本地");save.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e3) { String text = info.getText();int name = (int)System.currentTimeMillis();try { FileOutputStream fos = new FileOutputStream("d://"+name+".txt"); fos.write(text.getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); } } }); panel.add(save);frame.setBounds(150, 150, 500, 500);frame.setVisible(true);frame.setResizable(false);ArrayList<Packet> packetlist = allpackets.getpacketlist();Map<String,String> hm1 = new HashMap<String,String>();Map<String,String> hm2 = new HashMap<String,String>();Packet packet = packetlist.get(row);info.append("------------------------------------------------------------------------------\n");info.append("-------------------------------IP頭信息:-------------------------------\n");info.append("------------------------------------------------------------------------------\n");hm1 = new PacketAnalyze(packet).IPanalyze();for(Map.Entry<String,String> me1 : hm1.entrySet()){info.append(me1.getKey()+" : "+me1.getValue()+"\n");}hm2 = new PacketAnalyze(packet).packetClass();info.append("------------------------------------------------------------------------------\n");info.append("-----------------------------"+hm2.get("協議")+"頭信息:-----------------------------\n");info.append("------------------------------------------------------------------------------\n");for(Map.Entry<String,String> me : hm2.entrySet()){info.append(me.getKey()+" : "+me.getValue()+"\n");}}}});setResizable(false);setVisible(true);addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);} }); }private class CardActionListener implements ActionListener{NetworkInterface device;CardActionListener(NetworkInterface device){this.device = device;}public void actionPerformed(ActionEvent e) {allpackets.setDevice(device);allpackets.setFilter("");new Thread(allpackets).start(); //開啟抓包線程} } }總結
以上是生活随笔為你收集整理的网络嗅探器的设计(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Symbian S60平台手机软件开发
- 下一篇: 边界行动