-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip_packet.go
54 lines (45 loc) · 965 Bytes
/
ip_packet.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
package ftcp
import (
"fmt"
"golang.org/x/net/ipv4"
)
type IPPacket struct {
Header *ipv4.Header
buf []byte
}
func MakeIPPacket(buf []byte) (*IPPacket, error) {
header, err := ipv4.ParseHeader(buf)
if err != nil {
return nil, err
}
if len(buf) < header.TotalLen {
return nil, fmt.Errorf("ip_packet: buffer len %d < packet length %d", len(buf), header.TotalLen)
}
buf = buf[:header.TotalLen]
packet := &IPPacket{
buf: buf,
Header: header,
}
return packet, nil
}
func (p *IPPacket) String() string {
return p.Header.String()
}
func (p *IPPacket) Payload() []byte {
return p.buf[p.Header.Len:]
}
func IPChecksum(packet []byte) uint16 {
if len(packet) < 20 {
panic("Invalid packet length")
}
var sum tcpChecksum
sum.AddBuf(packet[0:10])
sum.AddBuf(packet[12:])
return sum.Sum()
}
func IPSetChecksum(packet []byte, sum uint16) {
if len(packet) < 20 {
panic("Invalid packet length")
}
be.PutUint16(packet[10:12], sum)
}