2.2 - Getting a List of Interfaces

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.

Note about special "any" device on Linux systems

http://www.tcpdump.org/pcap3_man.html wrote:

On Linux systems with 2.2 or later kernels, a device argument of "any" or NULL can be used to capture packets from all interfaces. snaplen specifies the maximum number of bytes to capture. If this value is less than the size of a packet that is captured, only the first snaplen bytes of that packet will be captured and provided as packet data. A value of 65535 should be sufficient, on most if not all networks, to capture all the data available from the packet. promisc specifies if the interface is to be put into promiscuous mode. (Note that even if this parameter is false, the interface could well be in promiscuous mode for some other reason.) For now, this doesn't work on the "any" device; if an argument of "any" or NULL is supplied, the promisc flag is ignored.