Get IP packet data from ByteBuffer

江枫思渺然 提交于 2019-12-11 01:41:03

问题


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);
}

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?


回答1:


I cant believe i didn't catch this earlier. I forgot to call packet.clear() after debugPacket(packet).



来源:https://stackoverflow.com/questions/37246063/get-ip-packet-data-from-bytebuffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!