简体   繁体   English

如何在Java中使用jpcap识别接收到的数据包是使用TCP还是UDP?

[英]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;" 我想在TCPPacket或UDPPacket中解析我收到的数据包,但是如果我写“ TCPPacket pac3 =(TCPPacket)数据包;” 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" 对于使用UDP作为传输层协议的数据包,我得到一个异常“线程“主”中的异常java.lang.ClassCastException:jpcap.packet.UDPPacket无法转换为jpcap.packet.TCPPacket”

How can I identify whether my received packet is using TCP or UDP? 如何确定收到的数据包是使用TCP还是UDP? Actually I want to get port numbers from a received packet. 实际上,我想从接收到的数据包中获取端口号。

The obvious answer to your question is to use the instanceof operator: 您问题的明显答案是使用instanceof运算符:

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. 我不知道JPCAP API,但请看一下是否可以进行API调用以询问数据包的类型。 Or perhaps you can set up two different mechanisms (channels, sockets, callbacks???) to receive UDP and TCP separately so you know the difference? 或者,也许您可​​以设置两种不同的机制(通道,套接字,回调???)分别接收UDP和TCP,以便您知道其中的区别?

可能是您可以在Java中使用instanceof运算符来确定数据包的类型。

It looks like there's no method, based on the api, that you can call. 似乎没有可以基于api调用的方法。 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. 通常,这种情况将在流中处理,在那里您具有TCP或UDP的流。 But unfortunately you don't. 但是不幸的是你没有。

You should be able to rely on instanceof , but obviously api reliance is preferred to instanceof . 您应该能够依赖instanceof ,但是显然api依赖比instanceof更受青睐。

Another option would be to use the header() method. 另一种选择是使用header()方法。 It appears the protocol is stored in the IP header, which you should have access to. 似乎该协议存储在IP标头中,您应该可以访问该标头。 This page appears to illustrate the IP header, and that 6 would be the protocol number for TCP, with 17 being UDP. 该页面似乎是为了说明IP标头,而6是TCP的协议号,17是UDP。

In fact, the constants jpcap.Packet.IPPROTO_TCP and jpcap.Packet.IPPROTO_UDP probably map to those values. 实际上,常量jpcap.Packet.IPPROTO_TCPjpcap.Packet.IPPROTO_UDP可能映射到这些值。 So it looks like your best bet is to parse the header. 因此,看起来最好的选择是解析标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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