Passing packets from kernel land to userland - libipq and Perl

I have been looking at packet sniffing for various applications for a while now. Problem is that my needs are more "real time/in-line" than "post capture processing" (ala libpcap and friends).

So here are some notes on my progress. Consider this part 1.

Since I am using Linux exclusively, I had another look at Netfilter. I discovered basically two tools I could use:
The later seems to be a replacement for libipq, but I could not find a lot of documentation and implementation notes, so I stick with libipq for now.

Since I am more confident in Perl, I was delighted to find a Perl interface to libipq - perlipq.

On Debian based systems, ensure you have the following packages installed:
If you also want to start looking inside the packets, you might need something like NetPacket::IP.

Here is a simple test you can do to see the interface in action. First create a basic firewall script (fw.sh) with the following:


iptables -F
iptables -A INPUT -j ACCEPT
iptables -A OUTPUT -j ACCEPT
iptables -t mangle -F
iptables -t mangle -A OUTPUT -p tcp -j QUEUE

Next, create a Perl script (test.pl):

package passer;
use strict;
$^W = 1;

use IPTables::IPv4::IPQueue qw(:constants);
use NetPacket::IP;

sub main

my ($queue, $msg);

$queue = new IPTables::IPv4::IPQueue() or die IPTables::IPv4::IPQueue->errstr;
$queue->set_mode( IPQ_COPY_PACKET, 1500 );

while (1) {

$msg = $queue->get_message() or die IPTables::IPv4::IPQueue->errstr;

my $pl = $msg->payload();
my $len = $msg->data_len();

eval {

my $ip = NetPacket::IP->decode( $pl );
my $ipsrc = $ip->{src_ip};
my $ipdest = $ip->{dest_ip};
print " > from $ipsrc to $ipdest -=> $len\n";


$queue->set_verdict($msg->packet_id(), NF_ACCEPT) > 0 or die IPTables::IPv4::IPQueue->errstr;



To start the monitoring, run the initial firewall script, then run the above Perl script.

To stop the script, simply press CTRL+C. All networking should also stop as the script no longer passes the accept back.

To reset the firewall script, run:

# iptables -t mangle -F ; iptables -F

That's it.

I still have a number of things I want to do, including:
Well, I will hopefully post more updates in the not too distant future. Until then, happy computing :-)

Additional Resources:

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?