-
Notifications
You must be signed in to change notification settings - Fork 2
/
payload.go
67 lines (56 loc) · 1.28 KB
/
payload.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
//
// Helpers for parsing and encoding a unified DHCP message,
// including the header and the options
//
package main
import (
"bytes"
"fmt"
"log"
)
type DHCPMessage struct {
Header *MessageHeader
Options *Options
}
func NewDhcpMessage() *DHCPMessage {
return &DHCPMessage{
Options: NewOptions(),
Header: &MessageHeader{},
}
}
func (m *DHCPMessage) Encode(buf *bytes.Buffer) error {
err := m.Header.Encode(buf)
if err != nil {
return fmt.Errorf("Writing dhcp header to our payload: %v", err)
}
err = m.Options.Encode(buf)
if err != nil {
return fmt.Errorf("Writing dhcp options to our payload: %v", err)
}
return nil
}
func ParseDhcpMessage(buf []byte) (*DHCPMessage, error) {
reader := bytes.NewReader(buf)
header, err := ParseMessageHeader(reader)
if err != nil {
return nil, err
}
// Parse arbitrary options
options := ParseOptions(reader)
// ClientAddr overriden by option?
// FIXME: verify if this logic is actually needed
if option, ok := options.Get(OPTION_REQUESTED_IP); ok {
if option.Header.Length == 4 {
ip, err := BytesToFixedV4(option.Data)
if err == nil {
header.ClientAddr = ip
} else {
log.Printf("Failed converting byte stream to fixed v4")
}
}
}
return &DHCPMessage{
Options: options,
Header: header,
}, nil
}