74 lines
1.4 KiB
Go
74 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
)
|
|
|
|
const (
|
|
padVal uint8 = 0x00 // Padded with NUL/null-bytes
|
|
alignLen int = 4 // 4-Byte alignment
|
|
)
|
|
|
|
var (
|
|
// See the examples/v4opts.go for how these bytes are constructed.
|
|
opts []byte = []byte{
|
|
// This is an example.
|
|
// Option 1
|
|
0x94, // Type 148, RTRALT (Router Alert) (RFC 2113)
|
|
0x04, // Length (4 bytes)
|
|
0x00, 0x00, // "Router shall examine packet"
|
|
// EOOL
|
|
0x00,
|
|
// Padding will go here.
|
|
}
|
|
)
|
|
|
|
func main() {
|
|
|
|
var optLen int
|
|
var padLen int
|
|
var pad []byte
|
|
|
|
optLen = len(opts)
|
|
|
|
fmt.Println("Before padding:")
|
|
// Prints:
|
|
/*
|
|
0x9404000000
|
|
(Length: 5)
|
|
*/
|
|
fmt.Printf("%#02x\n(Length: %d)\n\n", opts, optLen)
|
|
|
|
/*
|
|
The remainder of the current length divided by
|
|
alignLen (4) (modulo) is subtracted from the alignLen
|
|
to determine how much must be added to reach the next
|
|
"boundary". It's then modulo'd *again* to rule out
|
|
currently being on an alignment bounary.
|
|
*/
|
|
padLen = (alignLen - (optLen % alignLen)) % alignLen
|
|
// Prints:
|
|
/*
|
|
Pad length needed: 3
|
|
*/
|
|
fmt.Printf("Pad length needed:\t%d\n\n", padLen)
|
|
pad = bytes.Repeat([]byte{padVal}, padLen)
|
|
|
|
opts = append(opts, pad...)
|
|
|
|
// Alternatively, this can be implemented with a loop, though it's likely less efficient:
|
|
/*
|
|
for len(opts) % alignLen != 0 {}
|
|
opts = append(opts, padVal)
|
|
}
|
|
*/
|
|
|
|
// Prints:
|
|
/*
|
|
Padded:
|
|
0x9404000000000000
|
|
*/
|
|
fmt.Printf("Padded:\n%#x\n", opts)
|
|
}
|