Is there a way to make a linux system react or do something when pinged from another device, besides just sending a reply (or not)?
Detect and respond to ping in userspace
linux;networking;scripting
You can use Linux netfilter to intercept incoming pings and send them to userspace. This will do it:iptables -I INPUT -p icmp --icmp-type echo-request -j NFLOGYou can add any kind of iptables criteria like -s (source) in order to intercept only some pings and not others.Note that this does not cancel the kernel's handling of the original ping. It only sends a copy to userspace. If you plan to respond to the ping from userspace then you will want to prevent the kernel from also handling it so that there are not 2 replies. To implement that, just follow up the above with another iptables rule to drop the original:iptables -I INPUT -p icmp --icmp-type echo-request -j DROPIn order to receive the ping from userspace, you have to write some C code. The libnetfilter_log library is what you need. Here is some sample code which I wrote a few years ago that does exactly that:#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);    }callback is a function that gets called for each incoming packet. It is defined as something like this:static intcallback(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... */    ....}