如何使用 pcap4j 操作数据包并写入 pcap 文件 [英] How to manipulate packet and write to pcap file using pcap4j

查看:297
本文介绍了如何使用 pcap4j 操作数据包并写入 pcap 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个 pcap 文件并转到每个数据包.然后获取 IP 地址并对其进行操作.最后,我要把它写到一个新的pcap文件中.

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.

我使用 pcap4j 1.6.4 及以下版本获取源 IP 地址:

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();
}

正如我提到的,我得到了源 IP 地址,现在我不知道如何设置新的源 IP 地址并将其写入 NewFileName.

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.

任何帮助将不胜感激.

推荐答案

pcap4j 中的数据包对象是不可变的.但是,您可以基于现有数据包创建一个新数据包,然后使用 Builder.

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.

在以下代码段中,我正在创建一个新的修改数据包(假设 replace() 包含您创建新 IP 地址的逻辑):

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);

这篇关于如何使用 pcap4j 操作数据包并写入 pcap 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆