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_conntrack *ct; 13 char buf[4096]; 14 15 ct = nfct_new(); 16 if (ct == NULL) 17 return MNL_CB_OK; 18 19 nfct_nlmsg_parse(nlh, ct); 20 21 nfct_snprintf(buf, sizeof(buf), ct, NFCT_T_UNKNOWN, NFCT_O_DEFAULT, 0); 22 printf("%s\n", buf); 23 24 nfct_destroy(ct); 25 26 return MNL_CB_OK; 27 } 28 29 int main(void) 30 { 31 struct mnl_socket *nl; 32 struct nlmsghdr *nlh; 33 struct nfgenmsg *nfh; 34 char buf[MNL_SOCKET_BUFFER_SIZE]; 35 unsigned int seq, portid; 36 int ret; 37 38 nl = mnl_socket_open(NETLINK_NETFILTER); 39 if (nl == NULL) { 40 perror("mnl_socket_open"); 41 exit(EXIT_FAILURE); 42 } 43 44 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) { 45 perror("mnl_socket_bind"); 46 exit(EXIT_FAILURE); 47 } 48 portid = mnl_socket_get_portid(nl); 49 50 nlh = mnl_nlmsg_put_header(buf); 51 nlh->nlmsg_type = (NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_GET; 52 nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_DUMP; 53 nlh->nlmsg_seq = seq = time(NULL); 54 55 nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg)); 56 nfh->nfgen_family = AF_INET; 57 nfh->version = NFNETLINK_V0; 58 nfh->res_id = 0; 59 60 ret = mnl_socket_sendto(nl, nlh, nlh->nlmsg_len); 61 if (ret == -1) { 62 perror("mnl_socket_recvfrom"); 63 exit(EXIT_FAILURE); 64 } 65 66 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); 67 while (ret > 0) { 68 ret = mnl_cb_run(buf, ret, seq, portid, data_cb, NULL); 69 if (ret <= MNL_CB_STOP) 70 break; 71 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); 72 } 73 if (ret == -1) { 74 perror("mnl_socket_recvfrom"); 75 exit(EXIT_FAILURE); 76 } 77 78 mnl_socket_close(nl); 79 80 return 0; 81 } 82