1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-10 06:16:53 -05:00
v2fly/common/net/packetaddr/packetaddr.go
2022-01-03 15:55:18 +00:00

57 lines
1.4 KiB
Go

package packetaddr
import (
"bytes"
gonet "net"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
protocol.AddressFamilyByte(0x02, net.AddressFamilyIPv6),
)
// AttachAddressToPacket
// relinquish ownership of data
// gain ownership of the returning value
func AttachAddressToPacket(data *buf.Buffer, address gonet.Addr) (*buf.Buffer, error) {
packetBuf := buf.New()
udpaddr := address.(*gonet.UDPAddr)
port, err := net.PortFromInt(uint32(udpaddr.Port))
if err != nil {
return nil, err
}
err = addrParser.WriteAddressPort(packetBuf, net.IPAddress(udpaddr.IP), port)
if err != nil {
return nil, err
}
_, err = packetBuf.Write(data.Bytes())
if err != nil {
return nil, err
}
data.Release()
return packetBuf, nil
}
// ExtractAddressFromPacket
// relinquish ownership of data
// gain ownership of the returning value
func ExtractAddressFromPacket(data *buf.Buffer) (*buf.Buffer, gonet.Addr, error) {
packetBuf := buf.StackNew()
address, port, err := addrParser.ReadAddressPort(&packetBuf, bytes.NewReader(data.Bytes()))
if err != nil {
return nil, nil, err
}
addr := &gonet.UDPAddr{
IP: address.IP(),
Port: int(port.Value()),
Zone: "",
}
data.Advance(packetBuf.Len())
packetBuf.Release()
return data, addr, nil
}