Skip to content

Instantly share code, notes, and snippets.

@j-white
Last active April 7, 2020 00:47
Show Gist options
  • Save j-white/cd0a5b6537143f7874dd1e3aa2ad930d to your computer and use it in GitHub Desktop.
Save j-white/cd0a5b6537143f7874dd1e3aa2ad930d to your computer and use it in GitHub Desktop.
Replay PCAP data over a socket
package org.opennms;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.TimeUnit;
import org.pcap4j.core.BpfProgram;
import org.pcap4j.core.NotOpenException;
import org.pcap4j.core.PacketListener;
import org.pcap4j.core.PcapHandle;
import org.pcap4j.core.PcapNativeException;
import org.pcap4j.core.Pcaps;
import org.pcap4j.packet.TcpPacket;
public class App {
private static ByteBuffer toByteBuffer(String pcap, String filter) throws PcapNativeException, NotOpenException, InterruptedException {
final PcapHandle handle = Pcaps.openOffline(pcap, PcapHandle.TimestampPrecision.NANO);
handle.setFilter(filter, BpfProgram.BpfCompileMode.OPTIMIZE);
ByteBuffer byteBuffer = ByteBuffer.allocate(8192*64);
PacketListener listener = packet -> {
TcpPacket tcpPacket = packet.get(TcpPacket.class);
byte[] bytes = tcpPacket.getPayload().getRawData();
byteBuffer.put(bytes);
};
handle.loop(0, listener);
handle.close();
return byteBuffer;
}
public static void main( String[] args ) throws PcapNativeException, NotOpenException, InterruptedException {
String pcap = "/home/jesse/Downloads/bmp-reset-pcap/bmp-juniper.pcap";
String filter = "tcp dst port 11019";
String hostname = "localhost";
int port = 5000;
ByteBuffer bytes = toByteBuffer(pcap, filter);
int bytesAvail = bytes.position();
System.out.printf("Read %d bytes from .pcap\n", bytesAvail);
bytes.rewind();
bytes.limit(bytesAvail);
try (Socket socket = new Socket(hostname, port)) {
OutputStream os = socket.getOutputStream();
WritableByteChannel channel = Channels.newChannel(os);
channel.write(bytes);
System.out.println("All bytes sent. Sleeping...");
Thread.sleep(TimeUnit.MINUTES.toMillis(5));
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment