登录
首页 >  Golang >  Go问答

Golang ICMP 数据包发送

来源:stackoverflow

时间:2024-04-12 10:39:33 178浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《Golang ICMP 数据包发送》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我目前正在开发一个基于 go 的路由器,用于教育目的。

当尝试序列化我从主机转发的 icmp 数据包时,gopacket.icmpv4 结构的 .serializeto 函数似乎正在剥离 icmp 有效负载部分,并且仅包含类型、代码、校验和、id 和序列它返回到缓冲区的字节数组。

下面是我用来将 eth、ip 和 icmp 层发送到 wan 接口的代码。从 lan 接口收到这些层后,我对这些层所做的唯一更改是 icmp id、以太网 src/dst 和 ip src。

opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
buff := gopacket.NewSerializeBuffer()
_ = gopacket.SerializeLayers(buff, opts, ethLayer, ipLayer, icmpLayer)

发送之前的 icmp 层显示它有有效负载部分:

icmplayer = &{baselayer:{内容:[8 0 65 238 7 109 0 1] 有效负载:[122 238 50 94 15 84 7 0 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55]} typecode:echorequest checksum:53486 id:10000 seq:1}

客户端的 pcap lan 端向服务器发送 icmp 请求。

服务器的 pcap wan 端将请求转发到目的地。

如果需要任何其他信息,请告诉我,我试图提供尽可能多的背景信息。


解决方案


我最终发现 icmp 类 serializeto 函数在将其字节数组表示放入缓冲区时正在剥离有效负载。为了进行测试,我能够更改该函数以使用以下代码动态分配更多空间(如果数据包具有有效负载部分),然后将有效负载添加到缓冲区中。将将此作为 bug 发布在 git 上,以解决问题或指出为什么此用例是边缘情况。

// SerializeTo writes the serialized form of this layer into the
// SerializationBuffer, implementing gopacket.SerializableLayer.
// See the docs for gopacket.SerializableLayer for more info.
func (i *ICMPv4) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
    bytes, err := b.PrependBytes(len(i.Payload)+8)//8)
    if err != nil {
        return err
    }
    i.TypeCode.SerializeTo(bytes)
    binary.BigEndian.PutUint16(bytes[4:], i.Id)
    binary.BigEndian.PutUint16(bytes[6:], i.Seq)

    startIndex := 8
    for _, element := range i.Payload {
        bytes[startIndex] = byte(uint16(element))
        startIndex+= 1
    }

    if opts.ComputeChecksums {
        bytes[2] = 0
        bytes[3] = 0
        i.Checksum = tcpipChecksum(b.Bytes(), 0)
    }
    binary.BigEndian.PutUint16(bytes[2:], i.Checksum)

    return nil
}

今天关于《Golang ICMP 数据包发送》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>