| 1 |
#include <stdio.h> |
| 2 |
#include <stdlib.h> |
| 3 |
#include <time.h> |
| 4 |
|
| 5 |
#include <libmnl/libmnl.h> |
| 6 |
#include <libnetfilter_conntrack/libnetfilter_conntrack.h> |
| 7 |
|
| 8 |
static void print_label(struct nf_conntrack *ct, struct nfct_labelmap *map) |
| 9 |
{ |
| 10 |
unsigned int i, max; |
| 11 |
const struct nfct_bitmask *b = nfct_get_attr(ct, ATTR_CONNLABELS); |
| 12 |
if (!b) |
| 13 |
return; |
| 14 |
|
| 15 |
puts("labels:"); |
| 16 |
max = nfct_bitmask_maxbit(b); |
| 17 |
for (i = 0; i <= max; i++) { |
| 18 |
if (nfct_bitmask_test_bit(b, i)) |
| 19 |
printf("\t'%s' (%d)\n", map ? nfct_labelmap_get_name(map, i) : "", i); |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
static int data_cb(const struct nlmsghdr *nlh, void *data) |
| 24 |
{ |
| 25 |
struct nf_conntrack *ct; |
| 26 |
char buf[4096]; |
| 27 |
|
| 28 |
ct = nfct_new(); |
| 29 |
if (ct == NULL) |
| 30 |
return MNL_CB_OK; |
| 31 |
|
| 32 |
nfct_nlmsg_parse(nlh, ct); |
| 33 |
|
| 34 |
nfct_snprintf(buf, sizeof(buf), ct, NFCT_T_UNKNOWN, NFCT_O_DEFAULT, 0); |
| 35 |
printf("%s\n", buf); |
| 36 |
|
| 37 |
print_label(ct, data); |
| 38 |
|
| 39 |
nfct_destroy(ct); |
| 40 |
|
| 41 |
return MNL_CB_OK; |
| 42 |
} |
| 43 |
|
| 44 |
int main(void) |
| 45 |
{ |
| 46 |
struct mnl_socket *nl; |
| 47 |
struct nlmsghdr *nlh; |
| 48 |
struct nfgenmsg *nfh; |
| 49 |
char buf[MNL_SOCKET_BUFFER_SIZE]; |
| 50 |
unsigned int seq, portid; |
| 51 |
int ret; |
| 52 |
struct nfct_labelmap *l = nfct_labelmap_new(NULL); |
| 53 |
|
| 54 |
nl = mnl_socket_open(NETLINK_NETFILTER); |
| 55 |
if (nl == NULL) { |
| 56 |
perror("mnl_socket_open"); |
| 57 |
exit(EXIT_FAILURE); |
| 58 |
} |
| 59 |
|
| 60 |
if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) { |
| 61 |
perror("mnl_socket_bind"); |
| 62 |
exit(EXIT_FAILURE); |
| 63 |
} |
| 64 |
portid = mnl_socket_get_portid(nl); |
| 65 |
|
| 66 |
nlh = mnl_nlmsg_put_header(buf); |
| 67 |
nlh->nlmsg_type = (NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_GET; |
| 68 |
nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_DUMP; |
| 69 |
nlh->nlmsg_seq = seq = time(NULL); |
| 70 |
|
| 71 |
nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg)); |
| 72 |
nfh->nfgen_family = AF_UNSPEC; |
| 73 |
nfh->version = NFNETLINK_V0; |
| 74 |
nfh->res_id = 0; |
| 75 |
|
| 76 |
|
| 77 |
ret = mnl_socket_sendto(nl, nlh, nlh->nlmsg_len); |
| 78 |
if (ret == -1) { |
| 79 |
perror("mnl_socket_sendto"); |
| 80 |
exit(EXIT_FAILURE); |
| 81 |
} |
| 82 |
|
| 83 |
ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); |
| 84 |
|
| 85 |
|
| 86 |
while (ret > 0) { |
| 87 |
ret = mnl_cb_run(buf, ret, seq, portid, data_cb, l); |
| 88 |
if (ret <= MNL_CB_STOP) |
| 89 |
break; |
| 90 |
ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); |
| 91 |
} |
| 92 |
if (ret == -1) { |
| 93 |
perror("mnl_socket_recvfrom"); |
| 94 |
exit(EXIT_FAILURE); |
| 95 |
} |
| 96 |
|
| 97 |
if (l) |
| 98 |
nfct_labelmap_destroy(l); |
| 99 |
|
| 100 |
mnl_socket_close(nl); |
| 101 |
|
| 102 |
return 0; |
| 103 |
} |