kaitoy / pcap4j

A Java library for capturing, crafting, and sending packets.

Home Page:https://www.pcap4j.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Getting timestamp and src/dest IP addresses for UDP packet?

stodge opened this issue · comments

I'm using the following code:

packet = handle.getNextPacketEx().get(UdpPacket.class);
UdpHeader header = packet.getHeader();
Packet payload = packet.getPayload();

But I can't for the life of me work out how to get the timestamp and src/dest IP addresses. I must be missing something really obvious? Any suggestions appreciated.

Thanks

We use IpSelector to parse the raw input data and get a UpdPacket from ipPacket.payload, roughly like the below (with Log.d added to show how you can get the src/dest IP addresses). I'm not seeing where to get the timestamp easily, though, but I'm not using it. (Kotlin example)

private fun dataToIpPacket(inputData: ByteArray): IpPacket? {
    val ipPacket = runCatching {
        IpSelector.newPacket(inputData, 0, inputData.size) as IpPacket
    }

    Log.d(TAG, ipPacket.getOrNull()?.header?.dstAddr.toString())
    Log.d(TAG, ipPacket.getOrNull()?.header?.srcAddr.toString())

    ipPacket.exceptionOrNull()?.let {
        Log.i(TAG, "inputToIpPacket: Discarding invalid IP packet", it)
    }

    return ipPacket.getOrNull()?.let {
        if (it.payload is UdpPacket) {
            it
        } else {
            Log.d(TAG, "Ignored unknown packet type ${it.payload::class.java.simpleName}")
            null
        }
    }
}

Thanks. My packets from the PCAP file are all decoding as UnknownPacket; I guess I have more reading to do to understand why that is.

Packet p = IpSelector.newPacket(data, 0, data.length);

I added a filter, and all is tickety boo...

handle.setFilter("udp", BpfCompileMode.OPTIMIZE);

Well, except I still don't have the timestamp.

I really need the timestamp, and as this project appears to be dead, I'll have to look for an alternative. Thanks for your help, Doug.

Geez, how did I miss this?

PcapPacket packet = handle.getNextPacketEx();
Instant timestamp = packet.getTimestamp();

My original code was this, so no wonder I couldn't find the timestamp:

Packet packet = handle.getNextPacketEx();

Error between keyboard and chair!