1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/common/net/packetaddr/packetaddr.go

48 lines
1.2 KiB
Go
Raw Normal View History

2021-10-24 11:59:01 -04:00
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"
2021-11-20 18:24:21 -05:00
gonet "net"
2021-10-24 11:59:01 -04:00
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
protocol.AddressFamilyByte(0x02, net.AddressFamilyIPv6),
)
2021-11-20 18:24:21 -05:00
func AttachAddressToPacket(data []byte, address gonet.Addr) []byte {
2021-10-24 11:59:01 -04:00
packetBuf := buf.StackNew()
2021-11-20 18:24:21 -05:00
udpaddr := address.(*gonet.UDPAddr)
2021-10-24 11:59:01 -04:00
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)
}
2021-12-29 17:29:07 -05:00
//Incorrect buffer reuse
2021-10-24 11:59:01 -04:00
data = append(packetBuf.Bytes(), data...)
2021-12-29 17:29:07 -05:00
//packetBuf.Release()
2021-10-24 11:59:01 -04:00
return data
}
2021-11-20 18:24:21 -05:00
func ExtractAddressFromPacket(data []byte) ([]byte, gonet.Addr) {
2021-10-24 11:59:01 -04:00
packetBuf := buf.StackNew()
address, port, err := addrParser.ReadAddressPort(&packetBuf, bytes.NewReader(data))
if err != nil {
panic(err)
}
2021-11-20 18:24:21 -05:00
var addr = &gonet.UDPAddr{
2021-10-24 11:59:01 -04:00
IP: address.IP(),
Port: int(port.Value()),
Zone: "",
}
payload := data[int(packetBuf.Len()):]
2021-10-25 10:13:43 -04:00
packetBuf.Release()
2021-10-24 11:59:01 -04:00
return payload, addr
}