Parse a DatagramPacket after converting it to a byte array in Java

前端 未结 4 1198
日久生厌
日久生厌 2021-02-04 20:42

I am trying to parse a DatagramPacket that I will receive at a socket. I know the format of the packet I will receive, which is a DHCPREQUEST packet, but I don\'t think that rea

4条回答
  •  既然无缘
    2021-02-04 21:22

    What you do is write yourself some helper methods to extract 2 byte, 4 byte, etc values from the packet, reading the bytes and assembling them into Java short, int or whatever values.

    For example

        public short getShort(byte[] buffer, int offset) {
            return (short) ((buffer[offset] << 8) | buffer[offset + 1]);
        }
    

    Then you use these helper methods as often as you need to. (If you want to be fancy, you could have the methods update an attribute that holds the current position, so that you don't have to pass an offset argument.)


    Alternatively, if you were not worried by the overheads, you could wrap the byte array in ByteArrayInputStream and a DataInputStream, and use the latter's API to read bytes, shorts, ints, and so on. IIRC, DataInputStream assumes that numbers are represented in the stream in "network byte order" ... which is almost certainly what the DHCP spec mandates.

提交回复
热议问题