-
Notifications
You must be signed in to change notification settings - Fork 1
/
packetudp.go
90 lines (70 loc) · 1.56 KB
/
packetudp.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
package planet
const DATA_SIZE_BYTES = 15
const PACKET_UDP_HEADER_BYTES = 17
type PacketUDP struct {
Session uint32
Protocol uint16
Sequence uint16
Ack uint16
AckBitfield uint32
DataType uint8
DataSize uint16
Data []byte
}
func (p *PacketUDP) Write() []byte {
buffer := NewBuffer(PACKET_UDP_HEADER_BYTES + int(p.DataSize))
buffer.WriteUint32(p.Session)
buffer.WriteUint16(p.Protocol)
buffer.WriteUint16(p.Sequence)
buffer.WriteUint16(p.Ack)
buffer.WriteUint32(p.AckBitfield)
buffer.WriteUint8(p.DataType)
buffer.WriteUint16(p.DataSize)
buffer.WriteBytes(p.Data)
return buffer.Bytes()
}
func NewPacket(buf []byte) *PacketUDP {
if len(buf) < PACKET_UDP_HEADER_BYTES {
return nil
}
packetBuffer := NewBufferFromRef(buf)
_, err := packetBuffer.GetBytes(DATA_SIZE_BYTES)
if err != nil {
return nil
}
dataSize, err := packetBuffer.GetUint16()
if err != nil {
return nil
}
data, err := packetBuffer.GetBytes(int(dataSize))
if err != nil {
return nil
}
packetBuffer.Reset()
pckt := PacketUDP{DataSize: dataSize, Data: data}
pckt.Session, err = packetBuffer.GetUint32()
if err != nil {
return nil
}
pckt.Protocol, err = packetBuffer.GetUint16()
if err != nil {
return nil
}
pckt.Sequence, err = packetBuffer.GetUint16()
if err != nil {
return nil
}
pckt.Ack, err = packetBuffer.GetUint16()
if err != nil {
return nil
}
pckt.AckBitfield, err = packetBuffer.GetUint32()
if err != nil {
return nil
}
pckt.DataType, err = packetBuffer.GetUint8()
if err != nil {
return nil
}
return &pckt
}