Content-type: text/html; charset=UTF-8
#include <sys/socket.h> #include <linux/sock_diag.h> #include <linux/unix_diag.h> /* for UNIX domain sockets */ #include <linux/inet_diag.h> /* for IPv4 and IPv6 sockets */ diag_socket = socket(AF_NETLINK, socket_type, NETLINK_SOCK_DIAG);
In the request, the caller can specify additional information it would like to obtain about the socket, for example, memory information or information specific to the address family.
When requesting a list of sockets, the caller can specify filters that would be applied by the kernel to select a subset of sockets to report. For now, there is only the ability to filter sockets by state (connected, listening, and so on.)
Note that sock_diag reports only those sockets that have a name; that is, either sockets bound explicitly with bind(2) or sockets that were automatically bound to an address (e.g., by connect(2)). This is the same set of sockets that is available via /proc/net/unix, /proc/net/tcp, /proc/net/udp, and so on.
struct sock_diag_req {
    __u8 sdiag_family;
    __u8 sdiag_protocol;
};
The fields of this structure are as follows:
If the nlmsg_flags field of the struct nlmsghdr header has the NLM_F_DUMP flag set, it means that a list of sockets is being requested; otherwise it is a query about an individual socket.
Each object is the NLA (netlink attributes) list that is to be accessed with the RTA_* macros from rtnetlink(3) API.
struct unix_diag_req {
    __u8    sdiag_family;
    __u8    sdiag_protocol;
    __u16   pad;
    __u32   udiag_states;
    __u32   udiag_ino;
    __u32   udiag_show;
    __u32   udiag_cookie[2];
};
The fields of this structure are as follows:
sdiag_protocol
1 << TCP_LISTEN
struct unix_diag_vfs {
    __u32 udiag_vfs_dev;
    __u32 udiag_vfs_ino;
};
The fields of this structure are as follows:
struct unix_diag_rqlen {
    __u32 udiag_rqueue;
    __u32 udiag_wqueue;
};
The fields of this structure are as follows:
For established sockets: the amount of data in incoming queue.
For established sockets: the amount of memory available for sending.
The following attributes are reported back without any specific request:
The response to a query for UNIX domain sockets is represented as an array of
struct unix_diag_msg {
    __u8    udiag_family;
    __u8    udiag_type;
    __u8    udiag_state;
    __u8    pad;
    __u32   udiag_ino;
    __u32   udiag_cookie[2];
};
followed by netlink attributes.
The fields of this structure are as follows:
struct inet_diag_req_v2 {
    __u8    sdiag_family;
    __u8    sdiag_protocol;
    __u8    idiag_ext;
    __u8    pad;
    __u32   idiag_states;
    struct inet_diag_sockid id;
};
where struct inet_diag_sockid is defined as follows:
struct inet_diag_sockid {
    __be16  idiag_sport;
    __be16  idiag_dport;
    __be32  idiag_src[4];
    __be32  idiag_dst[4];
    __u32   idiag_if;
    __u32   idiag_cookie[2];
};
The fields of struct inet_diag_req_v2 are as follows:
struct inet_diag_meminfo {
    __u32 idiag_rmem;
    __u32 idiag_wmem;
    __u32 idiag_fmem;
    __u32 idiag_tmem;
};
The fields of this structure are as follows:
The fields of struct inet_diag_sockid are as follows:
The response to a query for IPv4 or IPv6 sockets is represented as an array of
struct inet_diag_msg {
    __u8    idiag_family;
    __u8    idiag_state;
    __u8    idiag_timer;
    __u8    idiag_retrans;
    struct inet_diag_sockid id;
    __u32   idiag_expires;
    __u32   idiag_rqueue;
    __u32   idiag_wqueue;
    __u32   idiag_uid;
    __u32   idiag_inode;
};
followed by netlink attributes.
The fields of this structure are as follows:
For other sockets: the amount of data in the incoming queue.
For other sockets: the amount of memory available for sending.
UNIX_DIAG_MEMINFO and INET_DIAG_SKMEMINFO were introduced in Linux 3.6.
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/sock_diag.h>
#include <linux/unix_diag.h>
static int
send_query(int fd)
{
    struct sockaddr_nl nladdr = {
        .nl_family = AF_NETLINK
    };
    struct
    {
        struct nlmsghdr nlh;
        struct unix_diag_req udr;
    } req = {
        .nlh = {
            .nlmsg_len = sizeof(req),
            .nlmsg_type = SOCK_DIAG_BY_FAMILY,
            .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP
        },
        .udr = {
            .sdiag_family = AF_UNIX,
            .udiag_states = -1,
            .udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER
        }
    };
    struct iovec iov = {
        .iov_base = &req,
        .iov_len = sizeof(req)
    };
    struct msghdr msg = {
        .msg_name = (void *) &nladdr,
        .msg_namelen = sizeof(nladdr),
        .msg_iov = &iov,
        .msg_iovlen = 1
    };
    for (;;) {
        if (sendmsg(fd, &msg, 0) < 0) {
            if (errno == EINTR)
                continue;
            perror("sendmsg");
            return -1;
        }
        return 0;
    }
}
static int
print_diag(const struct unix_diag_msg *diag, unsigned int len)
{
    if (len < NLMSG_LENGTH(sizeof(*diag))) {
        fputs("short response\n", stderr);
        return -1;
    }
    if (diag->udiag_family != AF_UNIX) {
        fprintf(stderr, "unexpected family %u\n", diag->udiag_family);
        return -1;
    }
    struct rtattr *attr;
    unsigned int rta_len = len - NLMSG_LENGTH(sizeof(*diag));
    unsigned int peer = 0;
    size_t path_len = 0;
    char path[sizeof(((struct sockaddr_un *) 0)->sun_path) + 1];
    for (attr = (struct rtattr *) (diag + 1);
             RTA_OK(attr, rta_len); attr = RTA_NEXT(attr, rta_len)) {
        switch (attr->rta_type) {
        case UNIX_DIAG_NAME:
            if (!path_len) {
                path_len = RTA_PAYLOAD(attr);
                if (path_len > sizeof(path) - 1)
                    path_len = sizeof(path) - 1;
                memcpy(path, RTA_DATA(attr), path_len);
                path[path_len] = '\0';
            }
            break;
        case UNIX_DIAG_PEER:
            if (RTA_PAYLOAD(attr) >= sizeof(peer))
                peer = *(unsigned int *) RTA_DATA(attr);
            break;
        }
    }
    printf("inode=%u", diag->udiag_ino);
    if (peer)
        printf(", peer=%u", peer);
    if (path_len)
        printf(", name=%s%s", *path ? "" : "@",
                *path ? path : path + 1);
    putchar('\n');
    return 0;
}
static int
receive_responses(int fd)
{
    long buf[8192 / sizeof(long)];
    struct sockaddr_nl nladdr = {
        .nl_family = AF_NETLINK
    };
    struct iovec iov = {
        .iov_base = buf,
        .iov_len = sizeof(buf)
    };
    int flags = 0;
    for (;;) {
        struct msghdr msg = {
            .msg_name = (void *) &nladdr,
            .msg_namelen = sizeof(nladdr),
            .msg_iov = &iov,
            .msg_iovlen = 1
        };
        ssize_t ret = recvmsg(fd, &msg, flags);
        if (ret < 0) {
            if (errno == EINTR)
                continue;
            perror("recvmsg");
            return -1;
        }
        if (ret == 0)
            return 0;
        const struct nlmsghdr *h = (struct nlmsghdr *) buf;
        if (!NLMSG_OK(h, ret)) {
            fputs("!NLMSG_OK\n", stderr);
            return -1;
        }
        for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {
            if (h->nlmsg_type == NLMSG_DONE)
                return 0;
            if (h->nlmsg_type == NLMSG_ERROR) {
                const struct nlmsgerr *err = NLMSG_DATA(h);
                if (h->nlmsg_len < NLMSG_LENGTH(sizeof(*err))) {
                    fputs("NLMSG_ERROR\n", stderr);
                } else {
                    errno = -err->error;
                    perror("NLMSG_ERROR");
                }
                return -1;
            }
            if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY) {
                fprintf(stderr, "unexpected nlmsg_type %u\n",
                        (unsigned) h->nlmsg_type);
                return -1;
            }
            if (print_diag(NLMSG_DATA(h), h->nlmsg_len))
                return -1;
        }
    }
}
int
main(void)
{
    int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
    if (fd < 0) {
        perror("socket");
        return 1;
    }
    int ret = send_query(fd) || receive_responses(fd);
    close(fd);
    return ret;
}