Java package: org.jnetpcap
When you want to capture packets directly from a live network, you first must acquire a list of available network interfaces and then choose which one to open. Interface names differ greatly on each platform and can change order at anytime even on the same system.
Therefore it is not usually easy to programmaticaly choose a network interface on behalf of the user, and usually that decision is left up to the user either through a configuration option in your application or some user interface that lets the user choose one interface.
There is a function provided by Pcap class to do retrieve a list of interfaces. It is Pcap.findAllDevs() function. It returns an integer error code and fills in a supplied collections List object with PcapIf objects. Each PcapIf is a separate interface found on this particular system.
List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
StringBuilder errbuf = new StringBuilder(); // For any error msgs
int r = Pcap.findAllDevs(alldevs, errbuf);
if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
System.err.printf("Can't read list of devices, error is %s", errbuf.toString());
return;
}
Notice that the supplied list to Pcap.findAllDevs() is a regular JRE list which is filled with interfaces. This was another place where following the actual native libpcap programming style did not make sense. So we use a much more java friendly list than a linked list of some objects.
The important thing we are trying to acquire is the name of the interface the user or your application is interested in capturing on. We can get the name of the interface using PcapIf.getName() method and pass that into Pcap.openLive() for example or build a menu for the user with it.
Once we have a network interface chose, its time for the next step which is to open that network interface for reading. PcapIf does not provide any methods directly to open interface, we have to use Pcap.openLive() for that, discussed in the section.