Getting incoming TTL in GO

谁说我不能喝 提交于 2021-02-19 05:34:22

问题


I'm struggling with a small project I am working on. I want to implement functionality in GO that allows me to set the IP header TTL on an outgoing UDP packet that I then send and view the received TTL on the other end. I have a tried using a number of connections provided by the 'net' library and have so far had no success (I can set the TTL but I can't read it). Can anyone suggest a way of sending and receiving UDP packets that provide access to the packet's TTL field?


回答1:


Set TTL:

var conn *icmp.PacketConn

// for IPv4
conn.IPv4PacketConn().SetTTL(p.ttl) 
conn.IPv4PacketConn().SetControlMessage(ipv4.FlagTTL, true)

// for IPv6
conn.IPv6PacketConn().SetHopLimit(p.ttl) 
conn.IPv6PacketConn().SetControlMessage(ipv6.FlagHopLimit, true)

Recieve TTL:

    var ttl, n int
    bytes := make([]byte, 512)
    if IPv4 {
        var cm *ipv4.ControlMessage
        n, cm, _, err = conn.IPv4PacketConn().ReadFrom(bytes)
        if cm != nil {
            ttl = cm.TTL
        }
    } else {
        var cm *ipv6.ControlMessage
        n, cm, _, err = conn.IPv6PacketConn().ReadFrom(bytes)
        if cm != nil {
            ttl = cm.HopLimit
        }
    }



来源:https://stackoverflow.com/questions/50109485/getting-incoming-ttl-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!