ping

package module
v0.0.0-...-7141d42 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2019 License: MIT Imports: 12 Imported by: 0

README

go-ping

GoDoc Circle CI

ICMP Ping library for Go, inspired by https://github.com/sparrc/go-ping

Here is a very simple example that sends & receives 3 packets:

pinger, err := ping.NewPinger("www.google.com", ping.CountOption(3))
if err != nil {
        panic(err)
}

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
pinger.Run(ctx) // blocks until finished
stats := pinger.Statistics() // get send/receive/rtt stats

Here is an example that emulates the unix ping command:


options := []ping.PingerOption{
        ping.RecvFuncOption(func(pkt *ping.Packet) {
                fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
                        pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
        }),
        ping.FinishFuncOption(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)
        }),
}

pinger, err := ping.NewPinger("www.google.com", ...options)
if err != nil {
        panic(err)
}

// listen for ctrl-C signal
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
	for _ = range c {
		pinger.Stop()
	}
}()



fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
pinger.Run(context.Background())

It sends ICMP packet(s) and waits for a response. If it receives a response, it calls the "receive" callback. When it's finished, it calls the "finish" callback.

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

Installation:

go get github.com/seanhoughton/go-ping

To install the native Go ping executable:

go get github.com/seanhoughton/go-ping/...
$GOPATH/bin/ping

Note on Linux Support:

This library attempts to send an "unprivileged" ping via UDP. On linux, this must be enabled by setting

sudo sysctl -w net.ipv4.ping_group_range="0   2147483647"

If you do not wish to do this, you can set pinger.SetPrivileged(true) and use setcap to allow your binary using go-ping to bind to raw sockets (or just run as super-user):

setcap cap_net_raw=+ep /bin/go-ping

See this blog and the Go icmp library for more details.

Note on Windows Support:

You must use ping.PrivilegedOption(true), otherwise you will receive an error:

Error listening for ICMP packets: socket: The requested protocol has not been configured into the system, or no implementation for it exists.

This should work without admin privileges. Tested on Windows 10.

Documentation

Overview

Package ping is an ICMP ping library seeking to emulate the unix "ping" command.

Here is a very simple example that sends & receives 3 packets:

pinger, err := ping.NewPinger("www.google.com")
if err != nil {
	panic(err)
}

pinger.Count = 3
pinger.Run() // blocks until finished
stats := pinger.Statistics() // get send/receive/rtt stats

Here is an example that emulates the unix ping command:

pinger, err := ping.NewPinger("www.google.com")
if err != nil {
	fmt.Printf("ERROR: %s\n", err.Error())
	return
}

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())
pinger.Run()

It sends ICMP packet(s) and waits for a response. If it receives a response, it calls the "receive" callback. When it's finished, it calls the "finish" callback.

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type IcmpData

type IcmpData struct {
	Bytes   []byte
	Tracker int64
}

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
}

Packet represents a received and processed ICMP echo packet.

type Pinger

type Pinger struct {

	// Debug runs in debug mode
	Debug bool

	// Number of packets sent
	PacketsSent int

	// Number of packets received
	PacketsRecv int

	// Tracker: Used to uniquely identify packet when non-priviledged
	Tracker int64
	// contains filtered or unexported fields
}

Pinger represents ICMP packet sender/receiver

func NewPinger

func NewPinger(addr string, options ...PingerOption) (*Pinger, error)

NewPinger returns a new Pinger struct pointer

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) Run

func (p *Pinger) Run(ctx context.Context) 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) 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 PingerOption

type PingerOption func(*Pinger) error

PingerOption allows you to customize the pinger instance

func CountOption

func CountOption(count int) PingerOption

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

func FinishFuncOption

func FinishFuncOption(f func(*Statistics)) PingerOption

FinishFuncOption sets the function to call when Pinger exits

func IntervalOption

func IntervalOption(interval time.Duration) PingerOption

IntervalOption is the wait time between each packet send. Default is 1s.

func PacketSizeOption

func PacketSizeOption(packetSize int) PingerOption

PacketSizeOption sets the size of packet being sent

func PrivilegedOption

func PrivilegedOption(privileged bool) PingerOption

PrivilegedOption 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 RecvFuncOption

func RecvFuncOption(f func(*Packet)) PingerOption

RecvFuncOption sets the function to call when Pinger receives and processes a packet

type Statistics

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

	// PacketsSent is the number of packets sent.
	PacketsSent 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