Reputation: 93
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:
}
}
}
Upvotes: 1
Views: 806
Reputation: 93
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)
Upvotes: 1