-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdial.go
59 lines (43 loc) · 994 Bytes
/
dial.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
package gognet
import (
"bytes"
"fmt"
"math/rand"
"net"
"time"
"github.com/egor-erm/gognet/network"
)
func randPort() int {
rand.Seed(time.Now().Unix())
return rand.Intn(2000) + 30000
}
func Dial(address *net.UDPAddr) (*net.UDPConn, error) {
la := &net.UDPAddr{IP: []byte{0, 0, 0, 0}, Port: randPort()}
ra := address
udpConn, err := net.DialUDP("udp", la, ra)
if err != nil {
panic(err)
}
buf := bytes.NewBuffer(make([]byte, 0))
packet := &network.OpenConnectionRequest1{Protocol: Protocol_Version}
packet.Write(buf)
_, err1 := udpConn.Write(buf.Bytes())
if err1 != nil {
panic(err1)
}
buf.Reset()
b := make([]byte, 1500)
n, err1 := udpConn.Read(b)
if err1 != nil {
panic(err1)
}
buf.Write(b[:n])
byt, _ := buf.ReadByte()
switch byt {
case network.IDOpenConnectionReply1:
return udpConn, nil
case network.IDIncompatibleProtocolVersion:
return nil, fmt.Errorf("protocol not supported")
}
return nil, fmt.Errorf("error open connection")
}