How to manipulate packet and write to pcap file using pcap4j

时光总嘲笑我的痴心妄想 提交于 2019-12-08 13:09:30

问题


I want to get through a pcap file and go to each packet. Then get IP Address and manipulate it. In the end, I'm going to write it into a new pcap file.

I use pcap4j version 1.6.4 and below is how I get the Source IP Address:

String fname = "FileName";
String dumpFile = "newFileName";
PcapHandle h = Pcaps.openOffline(fname);
PcapDumper dumper = h.dumpOpen(newFileName);
Packet p = null;
while ((p = h.getNextPacket()) != null) {
    IpV4Packet ip = p.get(IpV4Packet.class);
    Inet4Address srcAddr = ip.getHeader().getSrcAddr();
}

As I mentioned, I got the Source IP Address and now I don't know how to set the new Source IP Address and write it to NewFileName.

Any help would be appreciated.


回答1:


Packet objects in pcap4j are immutable. You can, however, create a new packet based on an existing one and then modify it, using a Builder.

In the following snippet, I'm creating a new modified packet (assuming replace() contains your logic of creating a new IP address):

        Packet.Builder builder = p.getBuilder();
        builder.get(IpV4Packet.Builder.class)
                .srcAddr(replace(srcAddr));

        Packet newPacket = builder.build();

You can then dump the created packet using:

        dumper.dump(newPacket);


来源:https://stackoverflow.com/questions/38303230/how-to-manipulate-packet-and-write-to-pcap-file-using-pcap4j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!