'ICMP Golang with raw socket, control message has nil value

I'm playing around with the ICMP raw socket of Golang. I'd like to read the TTL which is part the control message returned by ReadFrom(buffer).

Weirdly this value is always nil, is there something I'm missing.

Please find below my playground code:

package main

import (
    "fmt"
    "golang.org/x/net/icmp"
    "golang.org/x/net/ipv4"
)

func main() {

    c, _ := icmp.ListenPacket("ip4:icmp", "")

    rb := make([]byte, 1500)
    for true {

        n, cm, peer, _ := c.IPv4PacketConn().ReadFrom(rb)
        rm, _ := icmp.ParseMessage(ipv4.ICMPTypeEchoReply.Protocol(), rb[:n])

        switch rm.Type {
        case ipv4.ICMPTypeEchoReply:
            {
                fmt.Printf("received answer from %s\n", peer)
                if cm != nil {
                    println(cm.TTL)
                } else {
                    println("empty control message")
                }

            }
        default:

        }
    }
}


Solution 1:[1]

Finally, I found out what was missing.

Before reading, it is required to set IP socket options.

In my case, I was interested in TTL, so:

        _ = c.IPv4PacketConn().SetControlMessage(ipv4.FlagTTL, true)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DharmanBot