forked from oleksandr/bonjour
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathecho.go
77 lines (64 loc) · 1.36 KB
/
echo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package bonjour
import (
"errors"
"fmt"
"net"
"strings"
"time"
"github.com/socketplane/go-fastping"
)
type response struct {
addr *net.IPAddr
rtt time.Duration
}
const (
// EchoReply indicates that a reply was received
EchoReply = iota
// NoReply indicates that no reply was received
NoReply
// Error indicates that there was an error with the request
Error
)
func echo(address string, ip *net.IP) (int, error) {
p := fastping.NewPinger()
p.Debug = false
netProto := "ip4:icmp"
if strings.Index(address, ":") != -1 {
netProto = "ip6:ipv6-icmp"
}
ra, err := net.ResolveIPAddr(netProto, address)
if err != nil {
return Error, err
}
if ip != nil && ip.To4() != nil {
p.ListenAddr, _ = net.ResolveIPAddr("ip4", ip.To4().String())
}
results := make(map[string]*response)
results[ra.String()] = nil
p.AddIPAddr(ra)
onRecv, onIdle, onErr := make(chan *response), make(chan bool), make(chan int)
p.OnRecv = func(addr *net.IPAddr, t time.Duration) {
onRecv <- &response{addr: addr, rtt: t}
}
p.OnIdle = func() {
onIdle <- true
}
p.OnErr = func(addr *net.IPAddr, t int) {
onErr <- t
}
p.MaxRTT = time.Second
go p.Run()
ret := NoReply
select {
case <-onRecv:
ret = EchoReply
case <-onIdle:
ret = NoReply
case res := <-onErr:
errID := fmt.Sprintf("%d", res)
err = errors.New(errID)
ret = Error
}
p.Stop()
return ret, err
}