ping

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2021 License: MIT Imports: 16 Imported by: 0

README

go-ping-vrf

The popular ICMP Ping library for Go, modified to work when using vrf (Virtual Routing and Forwarding) in Linux

Original: https://github.com/go-ping/ping

Only Linux, only ICMP (meaning no UDP). Should work for IPv4 and IPv6.

# build
go build cmd/ping/ping.go

# ping 10.0.0.2 using the interface vrf-priv1 with the ip 10.0.0.2 continuously
ping -src 10.0.0.3 -if vrf-priv1 --privileged 10.0.0.2

Documentation

Overview

Package ping is a simple but powerful ICMP echo (ping) library.

Here is a very simple example that sends and receives three packets:

pinger, err := ping.NewPinger("www.google.com")
if err != nil {
	panic(err)
}
pinger.Count = 3
err = pinger.Run() // blocks until finished
if err != nil {
	panic(err)
}
stats := pinger.Statistics() // get send/receive/rtt stats

Here is an example that emulates the traditional UNIX ping command:

pinger, err := ping.NewPinger("www.google.com")
if err != nil {
	panic(err)
}
// Listen for Ctrl-C.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
	for _ = range c {
		pinger.Stop()
	}
}()
pinger.OnRecv = func(pkt *ping.Packet) {
	fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
		pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
}
pinger.OnFinish = func(stats *ping.Statistics) {
	fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
	fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
		stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
	fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
		stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
}
fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
err = pinger.Run()
if err != nil {
	panic(err)
}

It sends ICMP Echo Request packet(s) and waits for an Echo Reply in response. If it receives a response, it calls the OnRecv callback. When it's finished, it calls the OnFinish callback.

For a full ping example, see "cmd/ping/ping.go".

Index

Constants

View Source
const (
	ProtocolICMP     = 1  // Internet Control Message
	ProtocolIPv6ICMP = 58 // ICMP for IPv6
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Packet

type Packet struct {
	// Rtt is the round-trip time it took to ping.
	Rtt time.Duration

	// IPAddr is the address of the host being pinged.
	IPAddr *net.IPAddr

	// Addr is the string address of the host being pinged.
	Addr string

	// NBytes is the number of bytes in the message.
	Nbytes int

	// Seq is the ICMP sequence number.
	Seq int

	// TTL is the Time To Live on the packet.
	Ttl int
}

Packet represents a received and processed ICMP echo packet.

type PacketConn

type PacketConn struct {
	// contains filtered or unexported fields
}

A PacketConn represents a packet network endpoint that uses either ICMPv4 or ICMPv6.

func ListenPacket

func ListenPacket(network, address, sourceInterface string) (*PacketConn, error)

ListenPacket listens for incoming ICMP packets addressed to address. See net.Dial for the syntax of address.

For non-privileged datagram-oriented ICMP endpoints, network must be "udp4" or "udp6". The endpoint allows to read, write a few limited ICMP messages such as echo request and echo reply. Currently only Darwin and Linux support this.

Examples:

ListenPacket("udp4", "192.168.0.1")
ListenPacket("udp4", "0.0.0.0")
ListenPacket("udp6", "fe80::1%en0")
ListenPacket("udp6", "::")

For privileged raw ICMP endpoints, network must be "ip4" or "ip6" followed by a colon and an ICMP protocol number or name.

Examples:

ListenPacket("ip4:icmp", "192.168.0.1")
ListenPacket("ip4:1", "0.0.0.0")
ListenPacket("ip6:ipv6-icmp", "fe80::1%en0")
ListenPacket("ip6:58", "::")

func (*PacketConn) Close

func (c *PacketConn) Close() error

Close closes the endpoint.

func (*PacketConn) IPv4PacketConn

func (c *PacketConn) IPv4PacketConn() *ipv4.PacketConn

IPv4PacketConn returns the ipv4.PacketConn of c. It returns nil when c is not created as the endpoint for ICMPv4.

func (*PacketConn) IPv6PacketConn

func (c *PacketConn) IPv6PacketConn() *ipv6.PacketConn

IPv6PacketConn returns the ipv6.PacketConn of c. It returns nil when c is not created as the endpoint for ICMPv6.

func (*PacketConn) LocalAddr

func (c *PacketConn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*PacketConn) ReadFrom

func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error)

ReadFrom reads an ICMP message from the connection.

func (*PacketConn) SetDeadline

func (c *PacketConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the endpoint.

func (*PacketConn) SetReadDeadline

func (c *PacketConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline associated with the endpoint.

func (*PacketConn) SetWriteDeadline

func (c *PacketConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline associated with the endpoint.

func (*PacketConn) WriteTo

func (c *PacketConn) WriteTo(b []byte, dst net.Addr) (int, error)

WriteTo writes the ICMP message b to dst. The provided dst must be net.UDPAddr when c is a non-privileged datagram-oriented ICMP endpoint. Otherwise it must be net.IPAddr.

type Pinger

type Pinger struct {
	// Interval is the wait time between each packet send. Default is 1s.
	Interval time.Duration

	// Timeout specifies a timeout before ping exits, regardless of how many
	// packets have been received.
	Timeout time.Duration

	// Count tells pinger to stop after sending (and receiving) Count echo
	// packets. If this option is not specified, pinger will operate until
	// interrupted.
	Count int

	// Debug runs in debug mode
	Debug bool

	// Number of packets sent
	PacketsSent int

	// Number of packets received
	PacketsRecv int

	// Number of duplicate packets received
	PacketsRecvDuplicates int

	// If true, keep a record of rtts of all received packets.
	// Set to false to avoid memory bloat for long running pings.
	RecordRtts bool

	// OnSetup is called when Pinger has finished setting up the listening socket
	OnSetup func()

	// OnSend is called when Pinger sends a packet
	OnSend func(*Packet)

	// OnRecv is called when Pinger receives and processes a packet
	OnRecv func(*Packet)

	// OnFinish is called when Pinger exits
	OnFinish func(*Statistics)

	// OnDuplicateRecv is called when a packet is received that has already been received.
	OnDuplicateRecv func(*Packet)

	// Size of packet being sent
	Size int

	// Tracker: Used to uniquely identify packets
	Tracker uint64

	// Source is the source IP address
	Source string

	// SourceInterface is the source interface name
	SourceInterface string
	// contains filtered or unexported fields
}

Pinger represents a packet sender/receiver.

func New

func New(addr string) *Pinger

New returns a new Pinger struct pointer.

func NewPinger

func NewPinger(addr string) (*Pinger, error)

NewPinger returns a new Pinger and resolves the address.

func (*Pinger) Addr

func (p *Pinger) Addr() string

Addr returns the string ip address of the target host.

func (*Pinger) IPAddr

func (p *Pinger) IPAddr() *net.IPAddr

IPAddr returns the ip address of the target host.

func (*Pinger) Privileged

func (p *Pinger) Privileged() bool

Privileged returns whether pinger is running in privileged mode.

func (*Pinger) Resolve

func (p *Pinger) Resolve() error

Resolve does the DNS lookup for the Pinger address and sets IP protocol.

func (*Pinger) Run

func (p *Pinger) Run() error

Run runs the pinger. This is a blocking function that will exit when it's done. If Count or Interval are not specified, it will run continuously until it is interrupted.

func (*Pinger) SetAddr

func (p *Pinger) SetAddr(addr string) error

SetAddr resolves and sets the ip address of the target host, addr can be a DNS name like "www.google.com" or IP like "127.0.0.1".

func (*Pinger) SetIPAddr

func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr)

SetIPAddr sets the ip address of the target host.

func (*Pinger) SetNetwork

func (p *Pinger) SetNetwork(n string)

SetNetwork allows configuration of DNS resolution. * "ip" will automatically select IPv4 or IPv6. * "ip4" will select IPv4. * "ip6" will select IPv6.

func (*Pinger) SetPrivileged

func (p *Pinger) SetPrivileged(privileged bool)

SetPrivileged sets the type of ping pinger will send. false means pinger will send an "unprivileged" UDP ping. true means pinger will send a "privileged" raw ICMP ping. NOTE: setting to true requires that it be run with super-user privileges.

func (*Pinger) Statistics

func (p *Pinger) Statistics() *Statistics

Statistics returns the statistics of the pinger. This can be run while the pinger is running or after it is finished. OnFinish calls this function to get it's finished statistics.

func (*Pinger) Stop

func (p *Pinger) Stop()

type Statistics

type Statistics struct {
	// PacketsRecv is the number of packets received.
	PacketsRecv int

	// PacketsSent is the number of packets sent.
	PacketsSent int

	// PacketsRecvDuplicates is the number of duplicate responses there were to a sent packet.
	PacketsRecvDuplicates int

	// PacketLoss is the percentage of packets lost.
	PacketLoss float64

	// IPAddr is the address of the host being pinged.
	IPAddr *net.IPAddr

	// Addr is the string address of the host being pinged.
	Addr string

	// Rtts is all of the round-trip times sent via this pinger.
	Rtts []time.Duration

	// MinRtt is the minimum round-trip time sent via this pinger.
	MinRtt time.Duration

	// MaxRtt is the maximum round-trip time sent via this pinger.
	MaxRtt time.Duration

	// AvgRtt is the average round-trip time sent via this pinger.
	AvgRtt time.Duration

	// StdDevRtt is the standard deviation of the round-trip times sent via
	// this pinger.
	StdDevRtt time.Duration
}

Statistics represent the stats of a currently running or finished pinger operation.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL