5 #include <netinet/in.h>
6 #include <linux/types.h>
7 #include <linux/netfilter.h> /* for NF_ACCEPT */
10 #include <libnetfilter_queue/libnetfilter_queue.h>
12 /* returns packet id */
13 static u_int32_t print_pkt (struct nfq_data *tb)
16 struct nfqnl_msg_packet_hdr *ph;
17 struct nfqnl_msg_packet_hw *hwph;
22 ph = nfq_get_msg_packet_hdr(tb);
24 id = ntohl(ph->packet_id);
25 printf("hw_protocol=0x%04x hook=%u id=%u ",
26 ntohs(ph->hw_protocol), ph->hook, id);
29 hwph = nfq_get_packet_hw(tb);
31 int i, hlen = ntohs(hwph->hw_addrlen);
33 printf("hw_src_addr=");
34 for (i = 0; i < hlen-1; i++)
35 printf("%02x:", hwph->hw_addr[i]);
36 printf("%02x ", hwph->hw_addr[hlen-1]);
39 mark = nfq_get_nfmark(tb);
41 printf("mark=%u ", mark);
43 ifi = nfq_get_indev(tb);
45 printf("indev=%u ", ifi);
47 ifi = nfq_get_outdev(tb);
49 printf("outdev=%u ", ifi);
50 ifi = nfq_get_physindev(tb);
52 printf("physindev=%u ", ifi);
54 ifi = nfq_get_physoutdev(tb);
56 printf("physoutdev=%u ", ifi);
58 ret = nfq_get_payload(tb, &data);
60 printf("payload_len=%d ", ret);
68 static int cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg,
69 struct nfq_data *nfa, void *data)
71 u_int32_t id = print_pkt(nfa);
72 printf("entering callback\n");
73 return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
76 int main(int argc, char **argv)
79 struct nfq_q_handle *qh;
80 struct nfnl_handle *nh;
83 char buf[4096] __attribute__ ((aligned));
85 printf("opening library handle\n");
88 fprintf(stderr, "error during nfq_open()\n");
92 printf("unbinding existing nf_queue handler for AF_INET (if any)\n");
93 if (nfq_unbind_pf(h, AF_INET) < 0) {
94 fprintf(stderr, "error during nfq_unbind_pf()\n");
98 printf("binding nfnetlink_queue as nf_queue handler for AF_INET\n");
99 if (nfq_bind_pf(h, AF_INET) < 0) {
100 fprintf(stderr, "error during nfq_bind_pf()\n");
104 printf("binding this socket to queue '0'\n");
105 qh = nfq_create_queue(h, 0, &cb, NULL);
107 fprintf(stderr, "error during nfq_create_queue()\n");
111 printf("setting copy_packet mode\n");
112 if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) {
113 fprintf(stderr, "can't set packet_copy mode\n");
120 if ((rv = recv(fd, buf, sizeof(buf), 0)) >= 0) {
121 printf("pkt received\n");
122 nfq_handle_packet(h, buf, rv);
125 /* if your application is too slow to digest the packets that
126 * are sent from kernel-space, the socket buffer that we use
127 * to enqueue packets may fill up returning ENOBUFS. Depending
128 * on your application, this error may be ignored. Please, see
129 * the doxygen documentation of this library on how to improve
132 if (rv < 0 && errno == ENOBUFS) {
133 printf("losing packets!\n");
136 perror("recv failed");
140 printf("unbinding from queue 0\n");
141 nfq_destroy_queue(qh);
144 /* normally, applications SHOULD NOT issue this command, since
145 * it detaches other programs/sockets from AF_INET, too ! */
146 printf("unbinding from AF_INET\n");
147 nfq_unbind_pf(h, AF_INET);
150 printf("closing library handle\n");