从ByteBuffer获取IP数据包数据 [英] Get IP packet data from ByteBuffer
本文介绍了从ByteBuffer获取IP数据包数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从数据包中获取源地址和目标地址.这就是我阅读数据包的方式:
I'm trying to get the source and destination address from a packet. This is how i am reading the packet:
private void debugPacket(ByteBuffer packet) {
int buffer = packet.get();
int ipVersion = buffer >> 4;
int headerLength = buffer & 0x0F;
headerLength *= 4;
buffer = packet.get(); //DSCP + EN
int totalLength = packet.getChar(); //Total Length
buffer = packet.getChar(); //Identification
buffer = packet.getChar(); //Flags + Fragment Offset
buffer = packet.get(); //Time to Live
int protocol = packet.get(); //Protocol
buffer = packet.getChar(); //Header checksum
String sourceIP = "";
buffer = packet.get(); //Source IP 1st Octet
sourceIP += ((int) buffer) & 0xFF;
sourceIP += ".";
buffer = packet.get(); //Source IP 2nd Octet
sourceIP += ((int) buffer) & 0xFF;
sourceIP += ".";
buffer = packet.get(); //Source IP 3rd Octet
sourceIP += ((int) buffer) & 0xFF;
sourceIP += ".";
buffer = packet.get(); //Source IP 4th Octet
sourceIP += ((int) buffer) & 0xFF;
String destIP = "";
buffer = packet.get(); //Destination IP 1st Octet
destIP += ((int) buffer) & 0xFF;
destIP += ".";
buffer = packet.get(); //Destination IP 2nd Octet
destIP += ((int) buffer) & 0xFF;
destIP += ".";
buffer = packet.get(); //Destination IP 3rd Octet
destIP += ((int) buffer) & 0xFF;
destIP += ".";
buffer = packet.get(); //Destination IP 4th Octet
destIP += ((int) buffer) & 0xFF;
String hostName;
try {
InetAddress addr = InetAddress.getByName(destIP);
hostName = addr.getHostName();
} catch (UnknownHostException e) {
hostName = "Unresolved";
}
Log.d(this.getClass().getSimpleName(), "Packet: IP Version=" + ipVersion + ", Header-Length=" + headerLength + ", Total-Length=" + totalLength
+ ", Destination-IP=" + destIP + ", Hostname=" + hostName + ", Source-IP=" + sourceIP+ ", Protocol=" + protocol);
}
它对于前几个数据包工作正常,但是有时我在packet.get()
行之一中得到BufferUnderflowException.我该如何预防?
It works fine for the first few packets, but then sometimes i get a BufferUnderflowException at one of the packet.get()
lines. How can i prevent this?
推荐答案
我不敢相信我没有早点意识到这一点.我忘了在debugPacket(packet)
之后打电话给packet.clear()
.
I cant believe i didn't catch this earlier. I forgot to call packet.clear()
after debugPacket(packet)
.
这篇关于从ByteBuffer获取IP数据包数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文