How could I sniff network traffic in Java?

Java Is Cool picture Java Is Cool · Oct 2, 2014 · Viewed 39.3k times · Source

I was just looking around to find out how to make a program that would sniff my network traffic in Java, but I couldn't find anything. I wanted to know if there was any way to view the network traffic going by. I heard of an idea with a Socket, but I don't get how that would work. So anyways, just looking for an API or a way to write it myself.

EDIT: I would gladly like an API, but I would also like clarification on the way to sniff traffic with a Socket.

Answer

Byungjoon Lee picture Byungjoon Lee · Oct 2, 2014

jpcap, jNetPcap -- those are pcap wrapper projects in Java.

Kraken -- similar project, well documented with lots of examples.

simple example from the Kraken web site:

public static void main(String[] args) throws Exception {
    File f = new File("sample.pcap");

    EthernetDecoder eth = new EthernetDecoder();
    IpDecoder ip = new IpDecoder();
    TcpDecoder tcp = new TcpDecoder(new TcpPortProtocolMapper());
    UdpDecoder udp = new UdpDecoder(new UdpPortProtocolMapper());

    eth.register(EthernetType.IPV4, ip);
    ip.register(InternetProtocol.TCP, tcp);
    ip.register(InternetProtocol.UDP, udp);

    PcapInputStream is = new PcapFileInputStream(f);
    while (true) {
        // getPacket() will throws EOFException and you should call is.close() 
        PcapPacket packet = is.getPacket();
        eth.decode(packet);
    }
}