英文:
ICMP Golang with raw socket, control message has nil value
问题
我正在使用 Golang 的 ICMP 原始套接字进行实验。我想读取 TTL 值,该值是通过 ReadFrom(buffer) 返回的控制消息的一部分。
奇怪的是,这个值总是 nil,我是否漏掉了什么。
请查看下面的示例代码:
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:
}
}
}
希望对你有帮助!
英文:
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:
}
}
}
答案1
得分: 1
最后,我找到了缺少的部分。
在阅读之前,需要设置IP套接字选项。
在我的情况下,我对TTL感兴趣,所以:
_ = c.IPv4PacketConn().SetControlMessage(ipv4.FlagTTL, true)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论