Skip to content

Instantly share code, notes, and snippets.

@fqrouter
Created March 13, 2013 13:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fqrouter/5151855 to your computer and use it in GitHub Desktop.
Save fqrouter/5151855 to your computer and use it in GitHub Desktop.
A minimal application using libnetfilter_queue
#include <iostream>
#include <cstdlib>
#include <netinet/in.h>
extern "C" {
#include <linux/netfilter.h>
#include <libnetfilter_queue/libnetfilter_queue.h>
}
using namespace std;
void printBytes(char *input, int len) {
static const char* const lut = "0123456789ABCDEF";
char output[len * 2 + 1];
for (int i = 0; i < len ; ++i) {
const unsigned char c = input[i];
output[i * 2] = lut[c >> 4];
output[i * 2 + 1] = lut[c & 15];
}
output[len * 2] = '\0';
cout << output << endl;
}
static int handleNfq(nfq_q_handle *myQueue, struct nfgenmsg *msg, nfq_data *pkt, void *cbData) {
uint32_t id = 0;
nfqnl_msg_packet_hdr *header;
if ((header = nfq_get_msg_packet_hdr(pkt))) {
id = ntohl(header->packet_id);
}
char *payload;
int len = nfq_get_payload(pkt, &payload);
if (len) {
printBytes(payload, len);
}
return nfq_set_verdict(myQueue, id, NF_ACCEPT, 0, NULL);
}
int main(int argc, char **argv) {
struct nfq_handle *nfqHandle;
struct nfq_q_handle *myQueue;
int fd, res;
char buf[4096];
if (!(nfqHandle = nfq_open())) {
cerr << "Error in nfq_open()" << endl;
exit(-1);
}
if (nfq_unbind_pf(nfqHandle, AF_INET) < 0) {
cerr << "Error in nfq_unbind_pf()" << endl;
exit(1);
}
if (nfq_bind_pf(nfqHandle, AF_INET) < 0) {
cerr << "Error in nfq_bind_pf()" << endl;
exit(1);
}
if (!(myQueue = nfq_create_queue(nfqHandle, 0, &handleNfq, NULL))) {
cerr << "Error in nfq_create_queue()" << endl;
exit(1);
}
if (nfq_set_mode(myQueue, NFQNL_COPY_PACKET, 0xffff) < 0) {
cerr << "Could not set packet copy mode" << endl;
exit(1);
}
fd = nfq_fd(nfqHandle);
cerr << "fd: " << fd << endl;
while ((res = recv(fd, buf, sizeof(buf), 0)) && res >= 0) {
cerr << "res: " << res << endl;
nfq_handle_packet(nfqHandle, buf, res);
printBytes(buf, res);
}
nfq_destroy_queue(myQueue);
nfq_close(nfqHandle);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment