diff --git a/cmd/ping/ping.go b/cmd/ping/ping.go index 73fb2a8..0bed3fc 100644 --- a/cmd/ping/ping.go +++ b/cmd/ping/ping.go @@ -41,6 +41,7 @@ func main() { interval := flag.Duration("i", time.Second, "") count := flag.Int("c", -1, "") size := flag.Int("s", 24, "") + ttl := flag.Int("l", 64, "TTL") privileged := flag.Bool("privileged", false, "") flag.Usage = func() { fmt.Print(usage) @@ -88,6 +89,7 @@ func main() { pinger.Size = *size pinger.Interval = *interval pinger.Timeout = *timeout + pinger.TTL = *ttl pinger.SetPrivileged(*privileged) fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr()) diff --git a/packetconn.go b/packetconn.go index a590bfb..38e17e3 100644 --- a/packetconn.go +++ b/packetconn.go @@ -17,21 +17,38 @@ type packetConn interface { SetFlagTTL() error SetReadDeadline(t time.Time) error WriteTo(b []byte, dst net.Addr) (int, error) + SetTTL(ttl int) } type icmpConn struct { - c *icmp.PacketConn + c *icmp.PacketConn + ttl int } func (c *icmpConn) Close() error { return c.c.Close() } +func (c *icmpConn) SetTTL(ttl int) { + c.ttl = ttl +} + func (c *icmpConn) SetReadDeadline(t time.Time) error { return c.c.SetReadDeadline(t) } func (c *icmpConn) WriteTo(b []byte, dst net.Addr) (int, error) { + if c.c.IPv6PacketConn() != nil { + if err := c.c.IPv6PacketConn().SetHopLimit(c.ttl); err != nil { + return 0, err + } + } + if c.c.IPv4PacketConn() != nil { + if err := c.c.IPv4PacketConn().SetTTL(c.ttl); err != nil { + return 0, err + } + } + return c.c.WriteTo(b, dst) } diff --git a/ping.go b/ping.go index 8e78952..84637e3 100644 --- a/ping.go +++ b/ping.go @@ -106,6 +106,7 @@ func New(addr string) *Pinger { network: "ip", protocol: "udp", awaitingSequences: firstSequence, + TTL: 64, logger: StdLogger{Logger: log.New(log.Writer(), log.Prefix(), log.Flags())}, } } @@ -202,6 +203,8 @@ type Pinger struct { protocol string logger Logger + + TTL int } type packet struct { @@ -402,6 +405,7 @@ func (p *Pinger) Run() error { } defer conn.Close() + conn.SetTTL(p.TTL) return p.run(conn) } diff --git a/ping_test.go b/ping_test.go index 3cefb66..b8755e7 100644 --- a/ping_test.go +++ b/ping_test.go @@ -641,6 +641,7 @@ func (c testPacketConn) Close() error { return nil } func (c testPacketConn) ICMPRequestType() icmp.Type { return ipv4.ICMPTypeEcho } func (c testPacketConn) SetFlagTTL() error { return nil } func (c testPacketConn) SetReadDeadline(t time.Time) error { return nil } +func (c testPacketConn) SetTTL(t int) {} func (c testPacketConn) ReadFrom(b []byte) (n int, ttl int, src net.Addr, err error) { return 0, 0, nil, nil