1 Install Native Library

Let’s start with installing libpcap (for Mac/Linux/UNIX) or WinPcap (for Windows) on your computer. They are native libraries that powers the core functionalities of Pcap4J.

  • Ubuntu

    apt-get install libpcap-dev
    
  • CentOs

    yum install libpcap-devel
    
  • Mac

    brew install libpcap
    
  • Windows

    choco install winpcap
    

2 Add Dependencies

Before starting to write your code, you need to add Pcap4J and its dependencies to your classpath. The easiest way to do that is to use a build tool such as Gradle and Maven.

  • Gradle

    compile 'org.pcap4j:pcap4j-core:1.+'
    compile 'org.pcap4j:pcap4j-packetfactory-static:1.+'
    
  • Maven

    <dependency>
      <groupId>org.pcap4j</groupId>
      <artifactId>pcap4j-core</artifactId>
      <version>[1.0, 2.0)</version>
    </dependency>
    <dependency>
      <groupId>org.pcap4j</groupId>
      <artifactId>pcap4j-packetfactory-static</artifactId>
      <version>[1.0, 2.0)</version>
    </dependency>
    

3 Find Network Interface

It’s time to write your awesome application. Firstly, you probably want to find a network interface on which you want to capture packets.

InetAddress addr = InetAddress.getByName("192.168.10.100");
PcapNetworkInterface nif = Pcaps.getDevByAddress(addr);
Note: Administrator/root privileges or some Linux capabilities are needed.

4 Open Pcap Handle

Then, you can open a pcap handle from the network interface. A pcap handle provides you APIs to capture packets, send packets, and so on.

int snapLen = 65536;
PromiscuousMode mode = PromiscuousMode.PROMISCUOUS;
int timeout = 10;
PcapHandle handle = nif.openLive(snapLen, mode, timeout);

5 Capture Packet

Now you’ve got an ability to capture packets. Let’s get a packet using the pcap handle.

Packet packet = handle.getNextPacketEx();
handle.close();

6 Get Packet Information

The packet you captured consists of headers and payloads of some protocols such as Ethernet, IPv4, and TCP. The Packet API of Pcap4J enables you to get information from the protocol headers.

IpV4Packet ipV4Packet = packet.get(IpV4Packet.class);
Inet4Address srcAddr = ipV4Packet.getHeader().getSrcAddr();
System.out.println(srcAddr);

Learn More

Visit GitHub to learn more about Pcap4J!