libnetfilter_conntrack  1.0.6
nfct-mnl-event.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <arpa/inet.h>
5 
6 #include <libmnl/libmnl.h>
7 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
8 
9 static int data_cb(const struct nlmsghdr *nlh, void *data)
10 {
11  struct nf_conntrack *ct;
12  uint32_t type = NFCT_T_UNKNOWN;
13  char buf[4096];
14 
15  switch(nlh->nlmsg_type & 0xFF) {
16  case IPCTNL_MSG_CT_NEW:
17  if (nlh->nlmsg_flags & (NLM_F_CREATE|NLM_F_EXCL))
18  type = NFCT_T_NEW;
19  else
20  type = NFCT_T_UPDATE;
21  break;
22  case IPCTNL_MSG_CT_DELETE:
23  type = NFCT_T_DESTROY;
24  break;
25  }
26 
27  ct = nfct_new();
28  if (ct == NULL)
29  return MNL_CB_OK;
30 
31  nfct_nlmsg_parse(nlh, ct);
32 
33  nfct_snprintf(buf, sizeof(buf), ct,
34  type, NFCT_O_DEFAULT, 0);
35  printf("%s\n", buf);
36 
37  nfct_destroy(ct);
38 
39  return MNL_CB_OK;
40 }
41 
42 int main(void)
43 {
44  struct mnl_socket *nl;
45  char buf[MNL_SOCKET_BUFFER_SIZE];
46  int ret;
47 
48  nl = mnl_socket_open(NETLINK_NETFILTER);
49  if (nl == NULL) {
50  perror("mnl_socket_open");
51  exit(EXIT_FAILURE);
52  }
53 
54  if (mnl_socket_bind(nl, NF_NETLINK_CONNTRACK_NEW |
55  NF_NETLINK_CONNTRACK_UPDATE |
56  NF_NETLINK_CONNTRACK_DESTROY,
57  MNL_SOCKET_AUTOPID) < 0) {
58  perror("mnl_socket_bind");
59  exit(EXIT_FAILURE);
60  }
61 
62  while (1) {
63  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
64  if (ret == -1) {
65  perror("mnl_socket_recvfrom");
66  exit(EXIT_FAILURE);
67  }
68 
69  ret = mnl_cb_run(buf, ret, 0, 0, data_cb, NULL);
70  if (ret == -1) {
71  perror("mnl_cb_run");
72  exit(EXIT_FAILURE);
73  }
74  }
75 
76  mnl_socket_close(nl);
77 
78  return 0;
79 }
void nfct_destroy(struct nf_conntrack *ct)
Definition: conntrack/api.c:92
int nfct_snprintf(char *buf, unsigned int size, const struct nf_conntrack *ct, const unsigned int msg_type, const unsigned int out_type, const unsigned int out_flags)
struct nf_conntrack * nfct_new(void)
Definition: conntrack/api.c:75