Search code examples
javanetwork-programmingjpcap

How to identify whether a received packet is using TCP or UDP, in java using jpcap?


I want to parse my received packet in TCPPacket or UDPPacket, but if I write "TCPPacket pac3 = (TCPPacket) packet;" for a packet that is using UDP as transport layer protocol then I get an exception "Exception in thread "main" java.lang.ClassCastException: jpcap.packet.UDPPacket cannot be cast to jpcap.packet.TCPPacket"

How can I identify whether my received packet is using TCP or UDP? Actually I want to get port numbers from a received packet.


Solution

  • The obvious answer to your question is to use the instanceof operator:

    if (packet instanceof TCPPacket) {
        TCPPacket pac3 = (TCPPacket)packet;
        // ...
    }
    

    But that's a little bit smelly. I don't know the JPCAP API, but I would take a look to see if there's any API call you can make to ask the packet it's type. Or perhaps you can set up two different mechanisms (channels, sockets, callbacks???) to receive UDP and TCP separately so you know the difference?