github.com/MerlinKodo/sing-tun@v0.1.15/internal/clashtcpip/udp.go (about) 1 package clashtcpip 2 3 import ( 4 "encoding/binary" 5 ) 6 7 const UDPHeaderSize = 8 8 9 type UDPPacket []byte 10 11 func (p UDPPacket) Length() uint16 { 12 return binary.BigEndian.Uint16(p[4:]) 13 } 14 15 func (p UDPPacket) SetLength(length uint16) { 16 binary.BigEndian.PutUint16(p[4:], length) 17 } 18 19 func (p UDPPacket) SourcePort() uint16 { 20 return binary.BigEndian.Uint16(p) 21 } 22 23 func (p UDPPacket) SetSourcePort(port uint16) { 24 binary.BigEndian.PutUint16(p, port) 25 } 26 27 func (p UDPPacket) DestinationPort() uint16 { 28 return binary.BigEndian.Uint16(p[2:]) 29 } 30 31 func (p UDPPacket) SetDestinationPort(port uint16) { 32 binary.BigEndian.PutUint16(p[2:], port) 33 } 34 35 func (p UDPPacket) Payload() []byte { 36 return p[UDPHeaderSize:p.Length()] 37 } 38 39 func (p UDPPacket) Checksum() uint16 { 40 return binary.BigEndian.Uint16(p[6:]) 41 } 42 43 func (p UDPPacket) SetChecksum(sum [2]byte) { 44 p[6] = sum[0] 45 p[7] = sum[1] 46 } 47 48 func (p UDPPacket) ResetChecksum(psum uint32) { 49 p.SetChecksum(zeroChecksum) 50 p.SetChecksum(Checksum(psum, p)) 51 } 52 53 func (p UDPPacket) Valid() bool { 54 return len(p) >= UDPHeaderSize && uint16(len(p)) >= p.Length() 55 }