Developing lightweight computation at the DSG edge

ping.go 1.82 KB
Newer Older
1
2
3
4
5
package main

import (
	"flag"
	"fmt"
6
7
	"os"
	"os/signal"
8
9
10
11
12
13
14
15
	"time"

	"github.com/sparrc/go-ping"
)

var usage = `
Usage:

16
    ping [-c count] [-i interval] [-t timeout] [--privileged] host
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Examples:

    # ping google continuously
    ping www.google.com

    # ping google 5 times
    ping -c 5 www.google.com

    # ping google 5 times at 500ms intervals
    ping -c 5 -i 500ms www.google.com

    # ping google for 10 seconds
    ping -t 10s www.google.com
31
32
33

    # Send a privileged raw ICMP ping
    sudo ping --privileged www.google.com
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
`

func main() {
	timeout := flag.Duration("t", time.Second*100000, "")
	interval := flag.Duration("i", time.Second, "")
	count := flag.Int("c", -1, "")
	privileged := flag.Bool("privileged", false, "")
	flag.Usage = func() {
		fmt.Printf(usage)
	}
	flag.Parse()

	if flag.NArg() == 0 {
		flag.Usage()
		return
	}

	host := flag.Arg(0)
	pinger, err := ping.NewPinger(host)
	if err != nil {
		fmt.Printf("ERROR: %s\n", err.Error())
		return
	}

58
59
60
61
62
63
64
65
66
	// listen for ctrl-C signal
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			pinger.Stop()
		}
	}()

67
	pinger.OnRecv = func(pkt *ping.Packet) {
Clint Armstrong's avatar
Clint Armstrong committed
68
		fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v\n",
Roger Pueyo Centelles's avatar
Roger Pueyo Centelles committed
69
			pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.TTL)
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
	}
	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)
	}

	pinger.Count = *count
	pinger.Interval = *interval
	pinger.Timeout = *timeout
	pinger.SetPrivileged(*privileged)

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