I am trying to parse the DatagramPacket that I will get on the socket. I know the format of the packet that I will receive, which is the DHCPREQUEST packet, but I do not think it really matters. For simplicity, we consider only the first six fields:
The first field is the "opcode", which is 1 byte.
The second field is the “equipment type”, which is 1 byte.
Thirdly, "hardware address length", 1 byte.
Fourth, hop, 1 byte.
Fifth, "transaction id xid", 4 bytes.
Sixth, "seconds", 2 bytes.
After receiving the packet, my approach is to convert it to an array of bytes.
DatagramPacket request = new DatagramPacket(new byte[1024], 1024); socket.receive(request); byte[] buf = request.getData();
At this point, the packet is stored in the buf
byte array as a series of bytes. Since I know what the structure of this byte sequence is, how can I parse it? Single-byte fields are simple enough, but what about multi-bit fields? For example, how can I extract bytes 4 through 7 and store them in a variable called xid
?
I could manually put each byte in an array:
byte[] xid = new byte[4]; xid[0] = buf[4]; xid[1] = buf[5]; xid[2] = buf[6]; xid[3] = buf[7];
But this is just tedious and impractical for fields hundreds of bytes long. The String class can parse substrings based on offset and length; is there a similar method for byte arrays in java?
Or am I somehow complicating myself for myself?