我正在使用 pcp4j 为我的项目编写一个简单的数据包捕获和处理引擎。下面是我用来捕获数据包的代码,但是当我使用它只捕获环回地址上的传入数据包时,它会给我传出和传入的数据包。
如何区分环回地址上的传入和传出数据包?
public class PacketListner {
int packet_count = 0;
private static final String READ_TIMEOUT_KEY
= PacketListner.class.getName() + ".readTimeout";
private static final int READ_TIMEOUT
= Integer.getInteger(READ_TIMEOUT_KEY, 10); // [ms]
private static final String SNAPLEN_KEY
= PacketListner.class.getName() + ".snaplen";
private static final int SNAPLEN
= Integer.getInteger(SNAPLEN_KEY, 65536); // [bytes]
private static final String TIMESTAMP_PRECISION_NANO_KEY
= PacketListner.class.getName() + ".timestampPrecision.nano";
private static final boolean TIMESTAMP_PRECISION_NANO
= Boolean.getBoolean(TIMESTAMP_PRECISION_NANO_KEY);
public int sniff() throws PcapNativeException, NotOpenException {
PcapNetworkInterface nif = null;
try {
nif = new NifSelector().selectNetworkInterface();
} catch (IOException e) {
e.printStackTrace();
}
if (nif == null) {
return -1;
}
System.out.println(nif.getName() + "(" + nif.getDescription() + ")");
PcapHandle.Builder phb
= new PcapHandle.Builder(nif.getName())
.snaplen(SNAPLEN)
.direction(PcapHandle.PcapDirection.IN)
.promiscuousMode(PcapNetworkInterface.PromiscuousMode.PROMISCUOUS)
.timeoutMillis(READ_TIMEOUT);
if (TIMESTAMP_PRECISION_NANO) {
phb.timestampPrecision(PcapHandle.TimestampPrecision.NANO);
}
PcapHandle handle = phb.build();
while (true) {
Packet packet = handle.getNextPacket();
if (packet != null) {
if (packet.contains(IpV4Packet.class) &&
(packet.contains(TcpPacket.class) || packet.contains(UdpPacket.class))) {
IpV4Packet pkt = packet.get(IpV4Packet.class);
if (packet.contains (TcpPacket.class)) {
TcpPacket tcpPkt = packet.get(TcpPacket.class);
System.out.println(pkt.getHeader().getSrcAddr() + ":" + tcpPkt.getHeader().getDstPort());
}
else {
UDpPacket udpPkt = packet.get(UDpPacket.class);
System.out.println(pkt.getHeader().getSrcAddr() + ":" + udpPkt.getHeader().getDstPort());
}
}
packet_count++;
}
}
}
}