Skip to content

Instantly share code, notes, and snippets.

@Dragas
Created May 27, 2019 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dragas/2b414a7b6e0804e1cb8712e3c1e88718 to your computer and use it in GitHub Desktop.
Save Dragas/2b414a7b6e0804e1cb8712e3c1e88718 to your computer and use it in GitHub Desktop.
Simple hex dumping handler that mimicks wireshark for network based communication
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import java.nio.charset.Charset;
import java.util.Arrays;
public class HexDumpHandler extends ChannelInboundHandlerAdapter {
private static final int columnCount = 8;
private static final int groupCount = 32;
private static final Charset CHARSET = Charset.forName("UTF-8");
/**
* Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward
* to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
* <p>
* Sub-classes may override this method to change behavior.
*
* @param ctx
* @param msg
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//super.channelRead(ctx, msg);
final ByteBuf buffer = ((ByteBuf) msg);
int readableBytes = buffer.readableBytes();
byte[] data = new byte[readableBytes];
buffer.readBytes(data);
//int requiredPadding = groupCount - (readableBytes % groupCount);
for (int i = 0; i < readableBytes / groupCount + 1; i++) {
int maxlen = Math.min((i + 1) * groupCount, data.length);
byte[] column = Arrays.copyOfRange(data, i * groupCount, maxlen);
int originalLength = column.length;
column = Arrays.copyOf(column, groupCount);
Arrays.fill(column, originalLength, groupCount, (byte) 0x20);
for (int j = 0; j < column.length; j++) {
if(j > 0 && j % columnCount == 0)
System.out.print(" ");
System.out.print(String.format("%02x", column[j]));
}
System.out.print("\t");
System.out.println(new String(column, CHARSET)
.replaceAll("\r", " ")
.replaceAll("\n", " ")
.replaceAll(" ", "."));
}
System.out.println("- END -");
buffer.resetReaderIndex();
super.channelRead(ctx, msg);
//String data = buffer.getCharSequence(0, readableBytes, CHARSET).toString().replaceAll("\n", " 0x0A" + LINE_SEPARATOR);
//System.out.print(data);
//System.out.print("- END -");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment