2 #include <netinet/in.h>
3 #include <sys/socket.h>
5 #include <linux/netlink.h>
6 #include <linux/sock_diag.h>
7 #include <linux/inet_diag.h>
10 send_query(const int fd, const int family, const int proto)
12 struct sockaddr_nl nladdr = {
13 .nl_family = AF_NETLINK
17 struct inet_diag_req_v2 idr;
20 .nlmsg_len = sizeof(req),
21 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
22 .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
25 .sdiag_family = family,
26 .sdiag_protocol = proto,
32 .iov_len = sizeof(req)
35 .msg_name = (void*)&nladdr,
36 .msg_namelen = sizeof(nladdr),
42 if (sendmsg(fd, &msg, 0) < 0) {
52 parse_response(const struct inet_diag_msg *diag_msg, const unsigned long inode)
54 static const char zero_addr[sizeof(struct in6_addr)];
55 socklen_t addr_size, text_size;
57 if (diag_msg->idiag_inode != inode)
60 switch(diag_msg->idiag_family) {
62 addr_size = sizeof(struct in_addr);
63 text_size = INET_ADDRSTRLEN;
66 addr_size = sizeof(struct in6_addr);
67 text_size = INET6_ADDRSTRLEN;
73 char src_buf[text_size];
75 if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_src,
79 if (diag_msg->id.idiag_dport ||
80 memcmp(zero_addr, diag_msg->id.idiag_dst, addr_size)) {
81 char dst_buf[text_size];
83 if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_dst,
87 tprintf("%s:%u->%s:%u",
88 src_buf, ntohs(diag_msg->id.idiag_sport),
89 dst_buf, ntohs(diag_msg->id.idiag_dport));
91 tprintf("%s:%u", src_buf, ntohs(diag_msg->id.idiag_sport));
98 receive_responses(const int fd, const unsigned long inode)
100 static char buf[8192];
101 struct sockaddr_nl nladdr = {
102 .nl_family = AF_NETLINK
106 .iov_len = sizeof(buf)
112 struct msghdr msg = {
113 .msg_name = (void*)&nladdr,
114 .msg_namelen = sizeof(nladdr),
119 ret = recvmsg(fd, &msg, 0);
127 for (h = (struct nlmsghdr*)buf;
129 h = NLMSG_NEXT(h, ret)) {
130 switch (h->nlmsg_type) {
135 if (parse_response(NLMSG_DATA(h), inode))
141 /* Given an inode number of a socket, print out the details
142 * of the ip address and port. */
144 print_sockaddr_by_inode(const unsigned long inode)
146 const int families[] = {AF_INET, AF_INET6};
147 const int protocols[] = {IPPROTO_TCP, IPPROTO_UDP};
148 const size_t flen = ARRAY_SIZE(families);
149 const size_t plen = ARRAY_SIZE(protocols);
153 fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
157 for (fi = 0; fi < flen; ++fi) {
158 for (pi = 0; pi < plen; ++pi) {
159 if (!send_query(fd, families[fi], protocols[pi]))
161 if (receive_responses(fd, inode)) {