-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnect.go
68 lines (64 loc) · 1.33 KB
/
connect.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
package samil
import (
"net"
"time"
)
// Listens for incoming connections while advertising.
// Binds to given interface IP for advertising and listening.
func connect(interfaceIP net.IP) (*net.TCPConn, error) {
done := make(chan *net.TCPConn, 1)
fail := make(chan error, 1)
go func() {
conn, err := listen(interfaceIP)
if err != nil {
fail <- err
return
}
done <- conn
}()
for {
err := advertise(interfaceIP)
if err != nil {
return nil, err
}
timer := time.NewTimer(5 * time.Second)
select {
case conn := <-done:
return conn, nil
case err = <-fail:
return nil, err
case <-timer.C:
}
}
}
// Listens for incoming connections with a deadline of a minute.
func listen(interfaceIP net.IP) (*net.TCPConn, error) {
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{
IP: interfaceIP,
Port: 1200,
})
if err != nil {
return nil, err
}
defer listener.Close()
err = listener.SetDeadline(time.Now().Add(time.Minute))
if err != nil {
return nil, err
}
return listener.AcceptTCP()
}
// Advertises the existence of this client.
func advertise(interfaceIP net.IP) error {
socket, err := net.DialUDP("udp4", &net.UDPAddr{
IP: interfaceIP,
}, &net.UDPAddr{
IP: net.IPv4bcast,
Port: 1300,
})
if err != nil {
return err
}
_, err = socket.Write(advertisement)
socket.Close()
return err
}