libnetfilter_acct  1.0.3
nfacct-get.c
1 /* This example is in the public domain. */
2 #include <stdlib.h>
3 #include <string.h>
4 #include <time.h>
5 #include <libmnl/libmnl.h>
6 #include <libnetfilter_acct/libnetfilter_acct.h>
7 
8 static int nfacct_cb(const struct nlmsghdr *nlh, void *data)
9 {
10  struct nfacct *nfacct;
11  char buf[4096];
12 
13  nfacct = nfacct_alloc();
14  if (nfacct == NULL) {
15  perror("OOM");
16  goto err;
17  }
18 
19  if (nfacct_nlmsg_parse_payload(nlh, nfacct) < 0) {
20  perror("nfacct_parse_nl_msg");
21  goto err_free;
22  }
23 
24  nfacct_snprintf(buf, sizeof(buf), nfacct,
25  NFACCT_SNPRINTF_T_PLAIN, NFACCT_SNPRINTF_F_FULL);
26  printf("%s\n", buf);
27 
28 err_free:
29  nfacct_free(nfacct);
30 err:
31  return MNL_CB_OK;
32 }
33 
34 int main(int argc, char *argv[])
35 {
36  struct mnl_socket *nl;
37  char buf[MNL_SOCKET_BUFFER_SIZE];
38  struct nlmsghdr *nlh;
39  uint32_t portid, seq;
40  int ret, full = 1;
41  bool zeroctr = false;
42 
43  if (argc > 2) {
44  fprintf(stderr, "Usage: %s [-z]\n", argv[0]);
45  exit(EXIT_FAILURE);
46  }
47 
48  if (argc == 2 && strncmp(argv[1], "-z", strlen("-z")) == 0)
49  zeroctr = true;
50 
51  seq = time(NULL);
52  nlh = nfacct_nlmsg_build_hdr(buf, zeroctr ?
53  NFNL_MSG_ACCT_GET_CTRZERO :
54  NFNL_MSG_ACCT_GET,
55  NLM_F_DUMP, seq);
56 
57  nl = mnl_socket_open(NETLINK_NETFILTER);
58  if (nl == NULL) {
59  perror("mnl_socket_open");
60  exit(EXIT_FAILURE);
61  }
62 
63  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
64  perror("mnl_socket_bind");
65  exit(EXIT_FAILURE);
66  }
67  portid = mnl_socket_get_portid(nl);
68 
69  if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
70  perror("mnl_socket_send");
71  exit(EXIT_FAILURE);
72  }
73 
74  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
75  while (ret > 0) {
76  ret = mnl_cb_run(buf, ret, seq, portid, nfacct_cb, &full);
77  if (ret <= 0)
78  break;
79  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
80  }
81  if (ret == -1) {
82  perror("error");
83  exit(EXIT_FAILURE);
84  }
85  mnl_socket_close(nl);
86 
87  return EXIT_SUCCESS;
88 }
void nfacct_free(struct nfacct *nfacct)
int nfacct_nlmsg_parse_payload(const struct nlmsghdr *nlh, struct nfacct *nfacct)
struct nlmsghdr * nfacct_nlmsg_build_hdr(char *buf, uint8_t cmd, uint16_t flags, uint32_t seq)
struct nfacct * nfacct_alloc(void)
int nfacct_snprintf(char *buf, size_t size, struct nfacct *nfacct, uint16_t type, uint16_t flags)