简体   繁体   中英

How to identify whether a received packet is IPPacket or ARPPacket in java using jpcap?

I am capturing IPPackets and Analyze the captured packet in java using Jpcap Library.But captured packet is ARPPacket my program shows following error.

Blockquote

Exception in thread "main" java.lang.ClassCastException: jpcap.packet.ARPPacket cannot be cast to jpcap.packet.IPPacket.

Blockquote

so how can i identify whether received packet is IPPacket or ARPPacket. core concept of code is here:

import jpcap.*;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;
public class Capture  {
public static void main(String[] args) throws IOException {
    NetworkInterface[] device=JpcapCaptor.getDeviceList();
Packet packet;
    JpcapCaptor captor=JpcapCaptor.openDevice(device[0], 65535, true, 20);
for(;;){
 packet=captor.getPacket();       
 IPPacket p=(IPPacket)packet;
 if(p!=null)
   System.out.println("protocol id is"+p.protocol);
}
}
}

how can i overcame this error.thank you.

check the condition

if(packet instanceof ARPPacket) {
    ARPPacket arp = (ARPPacket) packet;
    // do somthing with ARPPacket
} else if(packet instanceof IPPacket) {
    // do something with IP Packet
    IPPacket arp = (IPPacket) packet;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM