I'm working on a packet sniffer but I'm getting trouble about the way to stop a thread (without deprecated methods) containing a blocking method.
The concerned method is the loop()
one from pcap4j library. As it is a blocking method, I put it into a thread to keep the main one working. However, in order to apply a filter to the pcap interface, I have to break the loop and restart it as the breakloop()
function of the library returns an InterruptedException
. So my idea was to kill the thread containing the method. But as I can't get into the library's loop causing the method to block, I'm unable to do it by checking whether the thread is interrupted or not.
Thread t = new Thread(new Runnable() {
@Override
public void run() {
loop(args);
}
});
t.start();
How can I stop it ?
EDIT : What I did was to recompile the library from its source, removing the InterruptedException from the PcapHandle class.
Using the Thread#getAllStackTraces you can obtain all the threads. SO Has a few other answers to this as well for getting a hold of the threads. After finding the thread you can interrupt it. The Thread.class
also has some other identifiers that may help find the thread too.
Edit: Are you using kaitoy/pcap4j ? if so breakLoop() Nothing can be done about the InterruptedException
, thats how the library intended for it to be broken. I would look at putting an issue in with their github if they need to implement a feature.
import java.util.Set;
class TestStuff {
public static void main(String[] args) {
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
if(thread.getName().equals("some-name")){
thread.interrupt();
}
}
}
}