github.com/yaling888/clash@v1.53.0/listener/tproxy/packet.go (about)

     1  package tproxy
     2  
     3  import (
     4  	"net"
     5  	"net/netip"
     6  
     7  	"github.com/yaling888/clash/common/pool"
     8  )
     9  
    10  type packet struct {
    11  	lAddr netip.AddrPort
    12  	bufP  *[]byte
    13  }
    14  
    15  func (c *packet) Data() *[]byte {
    16  	return c.bufP
    17  }
    18  
    19  // WriteBack opens a new socket binding `addr` to write UDP packet back
    20  func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
    21  	rAddr := addr.(*net.UDPAddr).AddrPort()
    22  	if c.lAddr.Addr().Is4() && rAddr.Addr().Is4In6() {
    23  		rAddr = netip.AddrPortFrom(rAddr.Addr().Unmap(), rAddr.Port())
    24  	}
    25  
    26  	tc, err := dialUDP("udp", rAddr, c.lAddr)
    27  	if err != nil {
    28  		n = 0
    29  		return
    30  	}
    31  	n, err = tc.Write(b)
    32  	_ = tc.Close()
    33  	return
    34  }
    35  
    36  // LocalAddr returns the source IP/Port of UDP Packet
    37  func (c *packet) LocalAddr() net.Addr {
    38  	return net.UDPAddrFromAddrPort(c.lAddr)
    39  }
    40  
    41  func (c *packet) Drop() {
    42  	pool.PutNetBuf(c.bufP)
    43  	c.bufP = nil
    44  }