2007-11-11
Passing packets from kernel land to userland - libipq and C
Based on my earlier entry, I got the C sample code working. Hopefully you will know what to do from the remarks in the code:
/*
* This code is GPL.
*/
/*
* Compiling: $ gcc -I/usr/include/libnetfilter_queue -L/usr/lib/libnetfilter_queue_libipq.so -o libipq_test_01 libipq_test_01.c -lipq
*
* You will require the following iptables rules BEFORE running this program:
*
* iptables -F
* iptables -A INPUT -j QUEUE
* iptables -A OUTPUT -j QUEUE
* iptables -A INPUT -j ACCEPT
* iptables -A OUTPUT -j ACCEPT
*
*/
#include
#include
#include
#define BUFSIZE 2048
static void die(struct ipq_handle *h)
{
ipq_perror("passer");
ipq_destroy_handle(h);
exit(1);
}
int main(int argc, char **argv)
{
int status;
unsigned char buf[BUFSIZE];
struct ipq_handle *h;
h = ipq_create_handle(0, PF_INET);
if (!h)
die(h);
status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE);
if (status < 0)
die(h);
fprintf( stderr, "Starting...\n" );
do{
status = ipq_read(h, buf, BUFSIZE, 0);
if (status < 0)
die(h);
switch (ipq_message_type(buf)) {
case NLMSG_ERROR:
fprintf(stderr, "Received error message %d\n",
ipq_get_msgerr(buf));
break;
case IPQM_PACKET: {
fprintf( stderr, "Processed packet\n" );
ipq_packet_msg_t *m = ipq_get_packet(buf);
status = ipq_set_verdict(h, m->packet_id,
NF_ACCEPT, 0, NULL);
if (status < 0)
die(h);
break;
}
default:
fprintf(stderr, "Unknown message type!\n");
break;
}
} while (1);
ipq_destroy_handle(h);
return 0;
}