github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/common/net/packetaddr/packetaddr.go (about)

     1  package packetaddr
     2  
     3  import (
     4  	"bytes"
     5  	gonet "net"
     6  
     7  	"github.com/v2fly/v2ray-core/v5/common/buf"
     8  	"github.com/v2fly/v2ray-core/v5/common/net"
     9  	"github.com/v2fly/v2ray-core/v5/common/protocol"
    10  )
    11  
    12  var addrParser = protocol.NewAddressParser(
    13  	protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
    14  	protocol.AddressFamilyByte(0x02, net.AddressFamilyIPv6),
    15  )
    16  
    17  // AttachAddressToPacket
    18  // relinquish ownership of data
    19  // gain ownership of the returning value
    20  func AttachAddressToPacket(data *buf.Buffer, address gonet.Addr) (*buf.Buffer, error) {
    21  	packetBuf := buf.New()
    22  	udpaddr := address.(*gonet.UDPAddr)
    23  	port, err := net.PortFromInt(uint32(udpaddr.Port))
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	err = addrParser.WriteAddressPort(packetBuf, net.IPAddress(udpaddr.IP), port)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	_, err = packetBuf.Write(data.Bytes())
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	data.Release()
    36  	return packetBuf, nil
    37  }
    38  
    39  // ExtractAddressFromPacket
    40  // relinquish ownership of data
    41  // gain ownership of the returning value
    42  func ExtractAddressFromPacket(data *buf.Buffer) (*buf.Buffer, gonet.Addr, error) {
    43  	packetBuf := buf.StackNew()
    44  	address, port, err := addrParser.ReadAddressPort(&packetBuf, bytes.NewReader(data.Bytes()))
    45  	if err != nil {
    46  		return nil, nil, err
    47  	}
    48  	addr := &gonet.UDPAddr{
    49  		IP:   address.IP(),
    50  		Port: int(port.Value()),
    51  		Zone: "",
    52  	}
    53  	data.Advance(packetBuf.Len())
    54  	packetBuf.Release()
    55  	return data, addr, nil
    56  }