forked from macdylan/sm2uploader
/
discover.go
104 lines (87 loc) · 2.19 KB
/
discover.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"log"
"net"
"time"
)
/* Discover discovers printers on the network. It returns a slice of
* pointers to Printer objects. If no printers are found, it returns
* an empty slice. If an error occurs, it returns nil.
*/
func Discover(timeout time.Duration) ([]*Printer, error) {
// Create a slice to hold the printers
printers := []*Printer{}
addrs, err := getBroadcastAddresses()
if err != nil {
return printers, err
}
for _, addr := range addrs {
// Create a new UDP broadcast address
broadcastAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", addr, 20054))
if err != nil {
return nil, err
}
// Create a new UDP connection
conn, err := net.ListenUDP("udp4", nil)
if err != nil {
return nil, err
}
defer conn.Close()
if Debug {
log.Printf("-- Discovering on %s", broadcastAddr)
}
// Set a timeout for the connection
conn.SetDeadline(time.Now().Add(timeout))
// Send the discover message
_, err = conn.WriteTo([]byte("discover"), broadcastAddr)
if err != nil {
return nil, err
}
// Create a buffer to hold the response
buf := make([]byte, 1500)
// Loop until the timeout is reached
for {
// Read the response
n, _, err := conn.ReadFromUDP(buf)
if err != nil {
// If the error is a timeout, break out of the loop
if err, ok := err.(net.Error); ok && err.Timeout() {
break
}
return nil, err
}
if Debug {
log.Printf("-- Discover got %d bytes %s", n, buf[:n])
}
// Parse the response into a Printer object
printer, err := NewPrinter(buf[:n])
if err != nil {
continue
}
// Add the printer to the slice
printers = append(printers, printer)
}
}
// Return the slice of printers
return printers, nil
}
func getBroadcastAddresses() ([]string, error) {
ifs, err := net.Interfaces()
if err != nil {
return nil, err
}
baddrs := make([]string, 0, len(ifs))
for _, iface := range ifs {
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if n, ok := addr.(*net.IPNet); ok && !n.IP.IsLoopback() && n.IP.To4() != nil {
baddrs = append(baddrs, n.IP.Mask(n.IP.DefaultMask()).String())
}
}
}
return baddrs, nil
}