How to listen to ICMP packets?

I am working on a two-part application where one side sends ICMP packets and the other side listens for ICMP packets and takes action when they are received. The problem is that I'm not sure how to keep the listener indefinitely (I just want him to sit there in a loop, only taking action when he receives the packet).

Currently, I can use the go-fastping library and send and receive packets if this is a two-way communication (I send it, they respond, process the remote response). The question is how to make this asymmetric?

My attempt to listen was:

for {
    conn, err := icmp.ListenPacket("ip4:icmp", "192.168.1.8")
    if err != nil {
        fmt.Println(err)
    }
}

but it does not work. My logic was that I want the loop to keep the while truelistener alive (in this case for {), then I listen to new packets with ICMP ListenPacket, but I don't seem to get anything using this approach.

Any ideas or help would be greatly appreciated. Thank you in advance for your time and help.

+4
source share
1 answer

icmp.ListenPacket()creates *icmp.PacketConn- in other words, the listener. You create listeners in an endless loop! Since you don’t even close them, your program will start complaining too many open filesfaster than you can say β€œping”.

Here is an example of a working listener

package main

import (
    "golang.org/x/net/icmp"
    "log"
)

func main() {
    conn, err := icmp.ListenPacket("ip4:icmp", "192.168.0.12")
    if err != nil {
        log.Fatal(err)
    }

    for {
        var msg []byte
        length, sourceIP, err := conn.ReadFrom(msg)
        if err != nil {
            log.Println(err)
            continue
        }

        log.Printf("message = '%s', length = %d, source-ip = %s", string(msg), length, sourceIP)
    }
    _ = conn.Close()
}

This gives:

2015/10/26 10:35:00 message = '', length = 0, source-ip = 192.168.0.7
2015/10/26 10:35:00 message = '', length = 0, source-ip = 192.168.0.25
2015/10/26 10:35:01 message = '', length = 0, source-ip = 192.168.0.7
2015/10/26 10:35:01 message = '', length = 0, source-ip = 192.168.0.25
2015/10/26 10:35:02 message = '', length = 0, source-ip = 192.168.0.7
2015/10/26 10:35:02 message = '', length = 0, source-ip = 192.168.0.25

.

, .

+7

Source: https://habr.com/ru/post/1613194/


All Articles