douben8492 2016-07-25 02:56
浏览 148
已采纳

无法在Golang中解析icmp消息

I'm a newb with Golang and trying to do what seems like a very simple task -- sending a ping with some text in it and reading that text back when I get a reply, but I'm running into some things I don't understand. I've built a ping like this:

 ping := icmp.Message{
    Type: ipv4.ICMPTypeEcho,
    Code: 0,
    Body: &icmp.Echo{
        ID: os.Getpid() & 0xffff,
        Seq: 1,
        Data: []byte("Hello"),
    },
}

Here's the socket read part for context:

buf := make([]byte, 1500)
_, peer, err := c.ReadFrom(buf)
message, err := icmp.ParseMessage(1, buf)

Here's my failed effort to get my data back out of the message body:

body := message.Body;
fmt.Println("body.ID ", body.ID)
fmt.Println("body.Seq ", body.Seq)
fmt.Println("body.Data ", string(body.Data))

Go is not happy at build time:

./ping.go:86: body.ID undefined (type icmp.MessageBody has no field or method ID)
./ping.go:87: body.Seq undefined (type icmp.MessageBody has no field or method Seq)
./ping.go:88: body.Data undefined (type icmp.MessageBody has no field or method Data)

This code, however, which is adapted from this awesome project, works just swell:

switch body := message.Body.(type) {
  case *icmp.Echo:
    fmt.Println("body.ID ", body.ID)
    fmt.Println("body.Seq ", body.Seq)
    fmt.Println("body.Data ", string(body.Data))
  default:
    fmt.Println("not a *icmp.Echo")
}

Go is perfectly happy to compile and run this code. Can someone tell me why the code in the type switch works fine, but the first example results in compile errors. Thank you!

  • 写回答

1条回答 默认 最新

  • douji7399 2016-07-25 06:06
    关注

    message.Body is a MessageBody (https://godoc.org/golang.org/x/net/icmp#MessageBody) which is an interface type. If you want the underlying type you need to cast it. One way to do that would be to say

    body := message.Body.(*icmp.Echo)
    ...
    

    This would likely work for you, but if the MessageBody is NOT an icmp.Echo pointer then it will be a panic.

    The type switch makes sure there is no panic.

    You could also do

    if body, ok := message.Body.(*icmp.Echo); ok {
        // do something with Body as an *icmp.Echo type
    }
    

    to guard against the panic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。