ICMP Golang使用原始套接字,控制消息的值为nil。

huangapple go评论78阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2022年5月7日 00:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/72144393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定