Reading header info from pcap packet

2.4k Views Asked by At

I have used following code to read Source and Destination IP from packet stored in pcap file. public void nextPacket(PcapPacket packet, String user) {

        Ip4 ip = new Ip4();
                    Ethernet eth=new Ethernet();
                    String sIP;
                    String dIP;
                    int totalLength=0;
                    if (packet.hasHeader(ip) == false){
                        return;
                    }
                     totalLength = totalLength+ ip.getPayloadLength();
                     sIP = org.jnetpcap.packet.format.FormatUtils.ip(ip.source());
                     dIP = org.jnetpcap.packet.format.FormatUtils.ip(ip.destination());
                     System.out.println("SIP = "+sIP+"  "+"destIP = "+dIP+" "+"Payload Length = "+ip.getPayloadLength());
                     System.out.println("Total Length = "+totalLength);
            }   

but it shows nothing, there are packets with the headers. Please help me.

2

There are 2 best solutions below

1
On

What do you mean it shows nothing? Is it just returning because the packet does not have a header or is it printing null's in the code at your end? I would have to guess with this little information that either the packet doesn't have an ip header.

0
On
PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>() {

        final Ip4 ip = new Ip4();
        public void nextPacket(PcapPacket packet, String user) {

            if(packet.hasHeader(Ip4.ID)){
                packet.getHeader(ip);
                byte[] dIP = new byte[4], sIP = new byte[4];
                dIP = packet.getHeader(ip).destination();
                sIP = packet.getHeader(ip).source();
                String sourceIP = FormatUtils.ip(sIP);
                String destinationIP = FormatUtils.ip(dIP);

                System.out.printf("tcp.ip_src=%s%n",sourceIP);
                System.out.printf("tcp.ip_dest=%s%n",destinationIP);
            }

        }
    };