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.

有帮助吗?

解决方案

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?

其他提示

May be you can use instanceof operator in java to determine the type of packet.

It looks like there's no method, based on the api, that you can call. If there was, it would be on the parent class of the packets, which is found here.

Typically this kind of thing would be dealt with in streams, where you have a stream of TCP or a stream of UDP. But unfortunately you don't.

You should be able to rely on instanceof, but obviously api reliance is preferred to instanceof.

Another option would be to use the header() method. It appears the protocol is stored in the IP header, which you should have access to. This page appears to illustrate the IP header, and that 6 would be the protocol number for TCP, with 17 being UDP.

In fact, the constants jpcap.Packet.IPPROTO_TCP and jpcap.Packet.IPPROTO_UDP probably map to those values. So it looks like your best bet is to parse the header.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top