检测并响应用户空间中的 ping

vic*_*cco 4 linux networking scripting

除了仅发送回复(或不发送)之外,有没有办法让 Linux 系统在从另一台设备 ping 时做出反应或执行某些操作?

Cel*_*ada 5

您可以使用 Linux netfilter 拦截传入的 ping 并将它们发送到用户空间。这将做到:

iptables -I INPUT -p icmp --icmp-type echo-request -j NFLOG
Run Code Online (Sandbox Code Playgroud)

您可以添加任何类型的 iptables 标准,例如-s(source),以便仅拦截某些 ping 而不是其他。

请注意,这不会取消内核对原始 ping 的处理。它只向用户空间发送一个副本。如果您打算响应来自用户空间的 ping,那么您将希望防止内核也处理它,以便没有 2 个回复。要实现这一点,只需按照上面的另一个 iptables 规则删除原始规则:

iptables -I INPUT -p icmp --icmp-type echo-request -j DROP
Run Code Online (Sandbox Code Playgroud)

为了从用户空间接收 ping,您必须编写一些 C 代码。该libnetfilter_log库是你需要的。这是我几年前写的一些示例代码,它正是这样做的:

#include <libnetfilter_log/libnetfilter_log.h>
[...]

    struct nflog_handle *h;
    struct nflog_g_handle *qh;
    ssize_t rv;
    char buf[4096];

    h = nflog_open();
    if (!h) {
            fprintf(stderr, "error during nflog_open()\n");
            return 1;
    }
    if (nflog_unbind_pf(h, AF_INET) < 0) {
            fprintf(stderr, "error nflog_unbind_pf()\n");
            return 1;
    }
    if (nflog_bind_pf(h, AF_INET) < 0) {
            fprintf(stderr, "error during nflog_bind_pf()\n");
            return 1;
    }
    qh = nflog_bind_group(h, 0);
    if (!qh) {
            fprintf(stderr, "no handle for group 0\n");
            return 1;
    }

    if (nflog_set_mode(qh, NFULNL_COPY_PACKET, 0xffff) < 0) {
            fprintf(stderr, "can't set packet copy mode\n");
            return 1;
    }

    nflog_callback_register(qh, &callback, NULL);

    fd = nflog_fd(h);

    while ((rv = recv(fd, buf, sizeof(buf), 0)) && rv >= 0) {
            nflog_handle_packet(h, buf, rv);
    }
Run Code Online (Sandbox Code Playgroud)

callback是为每个传入数据包调用的函数。它被定义为这样的:

static int
callback(struct nflog_g_handle *gh, struct nfgenmsg *nfmsg, struct nflog_data *ldata, void *data)
{
    payload_len = nflog_get_payload(ldata, (char **)(&ip));
    ....
    /* now "ip" points to the packet's IP header */
    /* ...do something with it... */
    ....
}
Run Code Online (Sandbox Code Playgroud)