I am reading packets from a pcap file. I want to keep it simple but I need to check for certain IP and TCP header options. I used the Pcap function nextEx to get a libpcap header and the packet contents as a JBuffer. What's the best way to now access the IP and TCP options? I looked around the examples and tried a few things but my code isn't able to detect if the packet is TCP correctly. Example is below.
Pcap pcapOffline = Pcap.openOffline(pcapFile, errbuf);
pcapOffline.nextEx(pkt_header, buffer);
Tcp tcpT = new Tcp();
PcapPacket offlinePacket = new PcapPacket(pkt_header, buffer);
if (offlinePacket.hasHeader(tcpT)) {
if (tcpT.flags_SYN() && !tcpT.flags_ACK())
numSyns++;
else if (tcpT.flags_FIN() || tcpT.flags_RST())
numCloses++;
else if (new String(buffer.getByteArray(tcpT.hlen(),
tcpT.getPayloadLength())).contains("GET http://"))
numGets++;
} else {
nonTCPPackets++;
}
The hasHeader check is always failing even when I know I have a TCP packet, why is that? Do I need to create a PcapPacket from the nextEx results before I can parse out the TCP options? If so why isn't there a nextEx call that will return a PcapPacket?
BTW, Is there a better way to get access to the TCP payload as a byte array so I can parse it for an HTTP get?
I have recently started on a multi-platform project, Linux, Windows & Mac and decided to try and add Mac support to jnetpcap. Below is an initial patch. It has not been tested thoroughly but the unit tests and the "Classic libpcap" example work. I will be giving it a more thorough shakeout over the next several months. For now, if anyone else is interested, please have a look.
Index: Mac OS X.properties
===================================================================
--- Mac OS X.properties (revision 0)
+++ Mac OS X.properties (revision 0)
@@ -0,0 +1,51 @@
+################################################################################
+#
+# Copyright (C) 2007 Sly Technologies, Inc.
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+################################################################################
+
+# Singleton
+platform.darwin = true
+platform.arch = ${os.arch}
+platform.os.name = ${os}
+
+# Top level
+rpm.src.dir = ${src.dir}/rpm
+rpm.build.dir = ${build.dir}/rpm
+rpm.buildroot.dir = ${basedir}/${rpm.build.dir}/INSTALL
+
+#
+lib.pcap.basename = jnetpcap Can I block or modify the packets instead of just capturing them?
I am trying to reconstruct a PcapPacket from a byte[] but I am getting the exception "java.lang.IllegalArgumentException: Invalid [offset,offset + length) range." being thrown.
Stack trace.
org.jnetpcap.nio.JMemory.peer(JMemory.java:383) org.jnetpcap.packet.JPacket$State.peerTo(JPacket.java:274) org.jnetpcap.packet.PcapPacket.peerStateAndData(PcapPacket.java:645) org.jnetpcap.packet.PcapPacket.transferStateAndDataFrom(PcapPacket.java:679) org.jnetpcap.packet.PcapPacket.(PcapPacket.java:382) com.kindsight.qa.utils.rpcap.TestServer.main(TestServer.java:40)
Here is my sample code.
final byte[] tmp = ... initialized outside of the scope of this example
PcapPacket tmpP = new PcapPacket(tmp);
System.out.println("Packet : \n" + tmpP.toHexdump());
Any ideas what I'm doing wrong?
There is an example of creating a filter here:
Are there any more examples? I would like to filter by protocol.
Thanks,
I have a pretty basic application which simply dumps out some packets from the network. I am however having a problem with my program not exiting after it breaks out of the pcap loop. Debugging the app indicates that the thread out_queue_pump is still running even though the main thread has been destroyed. What am I doing wrong?
Sample Code:
public static void main(String[] args) throws Exception {
StringBuilder errbuf = new StringBuilder();
pcap = Pcap.openLive("eth0", 64 * 1024, Pcap.MODE_NON_PROMISCUOUS,
60 * 1000, errbuf);
if (pcap == null) {
System.err.printf("Error while opening device for capture: %s\n",
errbuf.toString());
return;
}
PcapPacketHandler dumpHandler = new PcapPacketHandler() {
@Override
public void nextPacket(PcapPacket packet, PcapDumper user) {
System.out.println(packet.toHexdump());
}
};
PcapDumper user = new PcapDumper();
pcap.loop(10, dumpHandler, user);
System.out.println("Trying to shutdown");
pcap.close();
}
I am developing a tool that need to open a PCAP device (capturing packet as well as sending out).
The tool is in java (using eclipse as the IDE).
The function call :
org.jnetpcap.Pcap.findAllDevs(alldevs, errbuf);
is successfull, and I get a total of 4 devices.
When I call
pcap = Pcap.openLive("eth1", snaplen, flags, timeout, errbuf);
or
pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);
It always come back with pcap = null and the message in errbuf is :
Socket: Operation not permitted.
I ran wireshark (a sniffer tool) that is using the libpcap. When I ran it as a regular user
I couldn't find any interface available on the computer, I had to rerun it as user=root and
then all the interfaces (4 total) appear right away.
My question is what am I missing in the java world? do I need to run inside the java as "root"?
Once the tool is released, how can it be run by other users (none root)?
Please advice,
Natan Aviezri
naviezri@yahoo.com
Hi!
I don't have much technical feedback yet, except that I think fragment reassembly should be part of the API somehow, maybe in PcapPacketSupport.
I have some license feedback though; it appears that examples / tutorials also are LGPL in the same way that the library is. Technically/legally this makes it problematic to use the examples as a basis for commercial code since LGPL "works" differently for integrated code and dynamically linked libraries (such as the main jNetPcap library.
Therefore I suggest that you use a free'er license for the examples, for instance Apache 2.0 (considering it is a widely used Java license). If not, I would have to ask for variance on the fragment reassembly example 
I'm trying to access the data sections of received packets in an attempt to rip out a few fields. In turn, I will then use the sections to send a reply packet with the information from the original packet.
I've tried using jstream's LiveCapture to capture the packets in real time, but have run into consistent problems.
================
Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.nio.Buffer.checkIndex(Unknown Source)
at java.nio.HeapByteBuffer.get(Unknown Source)
at org.jnetstream.capture.file.pcap.PcapFile$1.readType(PcapFile.java:114)
at com.slytechs.file.pcap.PcapInputCapture.checkFormat(PcapInputCapture.java:67)
at com.slytechs.capture.StreamFactory.formatType(StreamFactory.java:73)
at com.slytechs.capture.FileFactory.formatType(FileFactory.java:80)
at com.slytechs.capture.FileFactory.openFile(FileFactory.java:244)
at com.slytechs.capture.DefaultCaptureFactory.catFile(DefaultCaptureFactory.java:129)
at org.jnetstream.capture.Captures.catFile(Captures.java:757)
at packet_capture.main(main.java:95)
================
Is there any way to capture received packets and access the raw data in jNetPcap?
Thanks,
In 1.2.rc5 in order to analyze packets, you have to go through a couple of extra steps, such as acquire a reference to JController and pass that into Pcap.loop method yourself. To make it a bit easier to use analysis, here are some additions targeted for 1.2.rc6.
Added a new interface JAnalyze which allows packets to be captured, decoded and analyzed directly from Pcap class. This interface is implemented by Pcap class and works just like its cousins Pcap.loop method. The difference is that Pcap.analyze methods takes a packet handler as an optional parameter. There are several variations of this method that take different types of parameters.
Pcap.analyze() (javadocs) - this method captures infinate amount of packets, or until the pcap capture is closed, decodes and analyzes the stream of packets. The captured packets are then dropped (consumed) by the outbound queue. The user is expected to register a protocol specific handler directly with a specific analyzer.
Pcap.analyze(int count) - same functionality as in #1, expect the number of packets captured is limited to the number specified.
Pcap.analyze(JPacketHandler handler, T user) - same functionality as in #1, except that packets are not consumed after the analysis, but dispatched to user supplied packet handler.
Pcap.analyze(int count, PacketHandler handler, T user) - same functionality as in #3, except the number of packets captured is limited to the number specified.
Here is an example that captures packets and analyzes them:
StringBuilder errbuf = new StringBuilder();
Pcap pcap = Pcap.openOffline("test/http.capture", errbuf);