The main goal is to detect open UDP ports by sending data over the port and listening for incoming ICMP messages if the port is unreachable. To do this, use the following Go function to run as a goroutine:
func listenIcmp(ipAddr string) { conn, err := icmp.ListenPacket("ip4:1", ipAddr) if err != nil { log.Println("Error while listening for ICMP packets: ") log.Println(err) } for { var incoming []byte length, sourceIP, err := conn.ReadFrom(incoming) if err != nil { log.Println(err) continue } log.Printf("message = '%s', length = %d, source-ip = %s", string(incoming), length, sourceIP) } }
This is able to detect ICMP pings and destination unreachability, but always returns a 0-length message. Example:
2023/10/11 14:38:32 Message = '', Length = 0, Source IP = 127.0.0.1
I have tried parsing the message but since it is empty it returns a runtime error. Also, I gave the go executable root permissions, but that didn't work either.
Edit: OS is Ubuntu 20.04
Caught my own mistake...
I try to read from an uninitialized buffer. Making the following changes to the incoming buffer resolves the issue:
// var incoming []byte incoming := make([]byte, 80)
The above is the detailed content of Only receive 0-length ICMP packets from icmp.Packetconn. For more information, please follow other related articles on the PHP Chinese website!