Only receive 0-length ICMP packets from icmp.Packetconn

WBOY
Release: 2024-02-05 21:24:04
forward
1208 people have browsed it

仅从 icmp.Packetconn 接收 0 长度的 ICMP 数据包

Question content

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)

    }
}
Copy after login

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


Correct answer


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)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template