Add ability to set TTL (#186)

This commit is contained in:
Cemre Mengu 2021-10-14 21:03:14 +03:00 committed by GitHub
parent 3818264768
commit 6e2b003bff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 1 deletions

View File

@ -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())

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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