Created
March 13, 2013 13:04
-
-
Save fqrouter/5151855 to your computer and use it in GitHub Desktop.
A minimal application using libnetfilter_queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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