Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Help in stopping thread (Packet sniffer)

  1. #1
    Junior Member
    Join Date
    Aug 2011
    Location
    Kuala Lumpur
    Posts
    2
    My Mood
    Inspired
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help in stopping thread (Packet sniffer)

    Hi! I'm confused with this code. I have a problem with stopping the thread. Can anybody help me?

    Thank you! Hope for your help guys.

    Code:
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import jpcap.JpcapCaptor;
    import jpcap.NetworkInterface;
    import jpcap.PacketReceiver;
    import jpcap.packet.*;
     
    public class MainGUI extends JFrame{
     
    	private JLabel lblintro;
    	public JTextArea txtPackets;
    	public JTextArea txtWarnings;
    	private JPanel panel1;
            private JPanel panel2;
            private JPanel panel3;
            private JPanel panel4;
            private JPanel panel5;
    	private JButton btnStart;
    	private JButton btnStop;
    	private JButton btnExit;
    	private JScrollPane sbrText;
    	public  JpcapCaptor jpcap;
    	public TestPacketReceiver TPR;
            protected JTabbedPane tabPane;
     
    	public MainGUI(){
     
    		super("Packet Sniffer");
     
                    tabPane = new JTabbedPane();
                    panel1 = new JPanel();
                    panel3 = new JPanel();
                    tabPane.addTab("Main menu", null,panel1,"First panel");
     
                    lblintro = new JLabel ("Packet Sniffer");
                    panel1.setLayout(new BorderLayout());
                    panel1.add(panel3,BorderLayout.NORTH);
     
                    panel3.setLayout(new FlowLayout());
                    panel3.add(lblintro);
     
                    btnStart = new JButton ("Start");
                    btnStart.addActionListener(new ButtonListener());
                    btnStop = new JButton ("Stop");
    		btnStop.addActionListener(new ButtonListener());
                    btnExit = new JButton ("Exit");
    		btnExit.addActionListener(new ButtonListener());
     
                    panel3.add(btnStart);
                    panel3.add(btnStop);
                    panel3.add(btnExit);
     
                    txtPackets = new JTextArea ();
                    txtPackets.setLineWrap(true);
    		txtPackets.setBorder(BorderFactory.createTitledBorder("Packets"));
                    panel1.add(txtPackets,BorderLayout.CENTER);
     
                    panel5 = new JPanel();
                    panel1.add(panel5,BorderLayout.SOUTH);
     
                    txtWarnings = new JTextArea ();
    		txtWarnings.setLineWrap(true);
                    txtWarnings.setBorder(BorderFactory.createTitledBorder("Warnings"));
                    panel1.add(txtWarnings,BorderLayout.SOUTH);
     
                    panel2 = new JPanel();
                    tabPane.addTab("Logs", null, panel2, "Second panel");
                    panel4 = new JPanel();
                    tabPane.addTab("Send alerts",null,panel4);
                    add(tabPane);                
    	}
     
     
    	 java.lang.Runnable rnner=new Runnable(){
                public void run(){
                    jpcap.loopPacket(-1, new TestPacketReceiver());
                }
             };
             Thread t;
     
    	 public void startCapThread(final JpcapCaptor jpcap){	  
                t =  new Thread(rnner);
                t.start();
             }    
     
    //////////////////// This part below is not working ////////////////////////
     
    	public void stopthread (final JpcapCaptor jpcap) {
                    t.stop();
     
    	}
     
     
    	public class ButtonListener implements ActionListener {
     
            @Override
                public void actionPerformed (ActionEvent e){		
    		if (e.getSource()==btnStart)
    		{
                        //JOptionPane.showMessageDialog(null, "Packet sniffer started");
                        try{
                            final NetworkInterface[] devices = JpcapCaptor.getDeviceList();
    			for(int i=0;i<devices.length;i++){
                                NetworkInterface nc=devices[i];
                            jpcap = JpcapCaptor.openDevice(nc, 2000, true, 20);
     
                            startCapThread(jpcap);
     
                            System.out.println("开始抓取第"+i+"个卡口上的数据");
    			}
                            }catch(Exception ef){
    			ef.printStackTrace();
    			System.out.println("启动失败:  "+ef);
                        }             
     
            	}
    		if (e.getSource()==btnStop)
    		{              
                        stopthread(jpcap);
                       // JOptionPane.showMessageDialog(null, "Packet sniffer stopped");
                        System.out.println("STOPPED");   
    		}
    		if (e.getSource()==btnExit)
    		{
                        System.exit(0);
    		}
     
                }
    	}  
     
    }

     class TestPacketReceiver  implements PacketReceiver {
    	  public String s;       
     
    	  public void receivePacket(Packet packet) {
    				 //Tcp, java Socket
     
    		  		if(packet instanceof jpcap.packet.TCPPacket){
    					TCPPacket p=(TCPPacket)packet;
                                    s="TCPPacket:| dst_ip "+p.dst_ip+":"+p.dst_port
                                    +"|src_ip "+p.src_ip+":"+p.src_port
                                    +" |len: "+p.len+" |flag: "+p.d_flag+" |ack_num: "+p.ack;
    				System.out.println(s);
     
     
    				}
    				//UDP, tcp+udp
    				else if(packet instanceof jpcap.packet.UDPPacket){
    					UDPPacket p=(UDPPacket)packet;
    					s="UDPPacket:| dst_ip "+p.dst_ip+":"+p.dst_port
    			         +"|src_ip "+p.src_ip+":"+p.src_port
    		            +" |len: "+p.len+" |THIS: "+p.d_flag;
    		           System.out.println(s);
     
    				}
    				//ping, ICMPPacket
    		       else if(packet instanceof jpcap.packet.ICMPPacket){
    		    	   ICMPPacket p=(ICMPPacket)packet;
    		    	   //ICMP
    		    	   String router_ip="";
    		    	   for(int i=0;i<p.router_ip.length;i++){
    		    		   router_ip+=" "+p.router_ip[i].getHostAddress();
    		    	   }
    					s="@ @ @ ICMPPacket:| router_ip "+router_ip
    					 +" |redir_ip: "+p.redir_ip
    					 +" |mtu: "+p.mtu
    		             +" |length: "+p.len+ " |This ICMP: "+p.addr_num;
    		          System.out.println(s);
     
    				}
     
    		       else if(packet instanceof jpcap.packet.ARPPacket){
    		    	   ARPPacket p=(ARPPacket)packet;
    		    	   //Returns the hardware address (MAC address) of the sender
    		    	   Object  saa=   p.getSenderHardwareAddress();
    		    	   Object  taa=p.getTargetHardwareAddress();
    		    	   s="* * * ARPPacket:| SenderHardwareAddress "+saa
    			         +"|TargetHardwareAddress "+taa
    		             +" |len: "+p.len;
    		         System.out.println(s);
     
    				}
     
    		     DatalinkPacket datalink  =packet.datalink;
     
    		     if(datalink instanceof jpcap.packet.EthernetPacket){
    		    	 EthernetPacket ep=(EthernetPacket)datalink;
    		    	  s="  datalink layer packet: "
    		    		  +"|DestinationAddress: "+ep.getDestinationAddress()
    		    		  +"|SourceAddress: "+ep.getSourceAddress();
    		    	  System.out.println(s);
     
    			}	 
    		  }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Help in stopping thread (Packet sniffer)

    In the thread add code to test a variable and exit if it is set.

    Please edit your code and wrap it in code tags. Use the #icon above input box.
    Or see: BB Code List - Java Programming Forums

  3. #3
    Junior Member
    Join Date
    Aug 2011
    Location
    Kuala Lumpur
    Posts
    2
    My Mood
    Inspired
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help in stopping thread (Packet sniffer)

    OK. thank you!

  4. #4
    Junior Member
    Join Date
    Sep 2011
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help in stopping thread (Packet sniffer)

    If you are going to use your own variable to indicate a request to stop then don't forget to make the variable 'volative' other wise the thread code may not see the changes made to it from other threads.

    Another robust approach is to use the interrupted flag. So within the thread code you would check the interrupted flag and return if set.

    if (Thread.interrupted()) {
       return
    }

    or maybe you want to keep doing something in a loop which you could aproach like this
    class InterruptableRunnable implements Runnable {
     while(!Thread.interrupted) {
          // do work in a loop
     } 
    }

    Then in in another thread, such as you GUI thread your code can stop the thread like this
    thread.interrupt();

    Another advantage of using the interrupted flag is that code serveral calls deeper from the runnable code can signal a request to be interrupted in a standard way, for example when performing some IO blocking operation

       try {
            socket.read();
      } catch (InterruptedException) {
          Thread.currentThread().interrupt();
    }

    Hope that helps

Similar Threads

  1. Stopping Graphics Animation.
    By SyntheticD in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 25th, 2011, 11:59 AM
  2. Stopping All Current Thread
    By newbie in forum Threads
    Replies: 1
    Last Post: November 26th, 2010, 08:27 PM
  3. While loop stopping?
    By Echo in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 16th, 2010, 05:40 PM
  4. Code stopping, need help fast.
    By aussiemcgr in forum What's Wrong With My Code?
    Replies: 2
    Last Post: August 11th, 2010, 09:00 AM
  5. Replies: 6
    Last Post: October 23rd, 2009, 03:53 AM