只是一个简单的计网课设
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
eruhs/core/parser/udp.go

45 lines
1.2 KiB

package parser
import (
"encoding/binary"
"fmt"
)
type UDP struct {
BaseLayer
SrcPort, DstPort uint16 // 源端口(可选)、目标端口
Length uint16 // 数据包总长(header+payload)
Checksum uint16 // 校验和(ipv4下可选)
}
func (U *UDP) LayerType() int {
return LayerTypeUDP
}
func DecodeUDP(data []byte) (*UDP, error) {
if len(data) < 8 {
return nil, fmt.Errorf("[UDP] 无效数据包长度: %d bytes, 至少需要8 bytes", len(data))
}
udp := UDP{}
udp.SrcPort = binary.BigEndian.Uint16(data[0:2])
udp.DstPort = binary.BigEndian.Uint16(data[2:4])
udp.Length = binary.BigEndian.Uint16(data[4:6])
udp.Checksum = binary.BigEndian.Uint16(data[6:8])
udp.Header = data[:8]
switch {
case udp.Length >= 8:
hlen := int(udp.Length)
if hlen > len(data) {
hlen = len(data)
}
udp.Payload = data[8:hlen]
case udp.Length == 0: // IPv6 Jumbogram, 剩下的所有数据都认为是payload
udp.Payload = data[8:]
default:
return nil, fmt.Errorf("[UDP] 数据包太小:%d bytes", udp.Length)
}
return &udp, nil
}