Home | History | Annotate | Download | only in examples
      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <unistd.h>
      4 #include <time.h>
      5 #include <arpa/inet.h>
      6 
      7 #include <libmnl/libmnl.h>
      8 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
      9 
     10 static int data_cb(const struct nlmsghdr *nlh, void *data)
     11 {
     12 	struct nf_expect *exp;
     13 	uint32_t type = NFCT_T_UNKNOWN;
     14 	char buf[4096];
     15 
     16 	exp = nfexp_new();
     17 	if (exp == NULL)
     18 		return MNL_CB_OK;
     19 
     20 	if (nfexp_nlmsg_parse(nlh, exp) < 0) {
     21 		perror("failed to parse message from kernel");
     22 		return MNL_CB_ERROR;
     23 	}
     24 
     25 	nfexp_snprintf(buf, sizeof(buf), exp, type, NFCT_O_DEFAULT, 0);
     26 	printf("%s\n", buf);
     27 
     28 	nfexp_destroy(exp);
     29 
     30 	return MNL_CB_OK;
     31 }
     32 
     33 int main(void)
     34 {
     35 	struct mnl_socket *nl;
     36 	char buf[MNL_SOCKET_BUFFER_SIZE];
     37 	struct nlmsghdr *nlh;
     38 	struct nfgenmsg *nfh;
     39 	uint32_t seq, portid;
     40 	int ret;
     41 
     42 	nl = mnl_socket_open(NETLINK_NETFILTER);
     43 	if (nl == NULL) {
     44 		perror("mnl_socket_open");
     45 		exit(EXIT_FAILURE);
     46 	}
     47 
     48 	if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
     49 		perror("mnl_socket_bind");
     50 		exit(EXIT_FAILURE);
     51 	}
     52 
     53 	portid = mnl_socket_get_portid(nl);
     54 
     55 	nlh = mnl_nlmsg_put_header(buf);
     56 	nlh->nlmsg_type = (NFNL_SUBSYS_CTNETLINK_EXP << 8) | IPCTNL_MSG_EXP_GET;
     57 	nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_DUMP|NLM_F_ACK;
     58 	nlh->nlmsg_seq = seq = time(NULL);
     59 
     60 	nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg));
     61 	nfh->nfgen_family = AF_INET;
     62 	nfh->version = NFNETLINK_V0;
     63 	nfh->res_id = 0;
     64 
     65 	ret = mnl_socket_sendto(nl, nlh, nlh->nlmsg_len);
     66 	if (ret == -1) {
     67 		perror("mnl_socket_recvfrom");
     68 		exit(EXIT_FAILURE);
     69 	}
     70 
     71 	ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
     72 	while (1) {
     73 		ret = mnl_cb_run(buf, ret, seq, portid, data_cb, NULL);
     74 		if (ret <= MNL_CB_STOP)
     75 			break;
     76 
     77 		ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
     78 	}
     79 	if (ret == -1) {
     80 		perror("mnl_socket_recvfrom");
     81 		exit(EXIT_FAILURE);
     82 	}
     83 
     84 	mnl_socket_close(nl);
     85 
     86 	return 0;
     87 }
     88