mirror of
https://github.com/v2fly/v2ray-core.git
synced 2024-11-12 07:19:01 -05:00
packet header encoder decoder
This commit is contained in:
parent
ac65036808
commit
1ec1bbffa4
45
common/net/packetaddr/packetaddr.go
Normal file
45
common/net/packetaddr/packetaddr.go
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
package packetaddr
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"github.com/v2fly/v2ray-core/v4/common/buf"
|
||||||
|
"github.com/v2fly/v2ray-core/v4/common/net"
|
||||||
|
"github.com/v2fly/v2ray-core/v4/common/protocol"
|
||||||
|
sysnet "net"
|
||||||
|
)
|
||||||
|
|
||||||
|
var addrParser = protocol.NewAddressParser(
|
||||||
|
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
|
||||||
|
protocol.AddressFamilyByte(0x02, net.AddressFamilyIPv6),
|
||||||
|
)
|
||||||
|
|
||||||
|
func AttachAddressToPacket(data []byte, address sysnet.Addr) []byte {
|
||||||
|
packetBuf := buf.StackNew()
|
||||||
|
udpaddr := address.(*sysnet.UDPAddr)
|
||||||
|
port, err := net.PortFromInt(uint32(udpaddr.Port))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
err = addrParser.WriteAddressPort(&packetBuf, net.IPAddress(udpaddr.IP), port)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
data = append(packetBuf.Bytes(), data...)
|
||||||
|
packetBuf.Release()
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExtractAddressFromPacket(data []byte) ([]byte, sysnet.Addr) {
|
||||||
|
packetBuf := buf.StackNew()
|
||||||
|
address, port, err := addrParser.ReadAddressPort(&packetBuf, bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
var addr = &sysnet.UDPAddr{
|
||||||
|
IP: address.IP(),
|
||||||
|
Port: int(port.Value()),
|
||||||
|
Zone: "",
|
||||||
|
}
|
||||||
|
payload := data[int(packetBuf.Len()):]
|
||||||
|
return payload, addr
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user