代码之家  ›  专栏  ›  技术社区  ›  TychoTheTaco

从ByteBuffer获取IP数据包数据

  •  2
  • TychoTheTaco  · 技术社区  · 10 年前

    我正在尝试从数据包中获取源地址和目标地址。这是我阅读数据包的方式:

    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() 线我怎样才能避免这种情况?

    1 回复  |  直到 7 年前
        1
  •  1
  •   TychoTheTaco    10 年前

    我真不敢相信我之前没赶上。我忘记打电话了 packet.clear() 之后 debugPacket(packet) .