github.com/yaling888/clash@v1.53.0/adapter/outbound/util.go (about)

     1  package outbound
     2  
     3  import (
     4  	"net"
     5  	"time"
     6  
     7  	"github.com/yaling888/clash/common/pool"
     8  	"github.com/yaling888/clash/component/resolver"
     9  	C "github.com/yaling888/clash/constant"
    10  	"github.com/yaling888/clash/transport/socks5"
    11  )
    12  
    13  func tcpKeepAlive(c net.Conn) {
    14  	if tcp, ok := c.(*net.TCPConn); ok {
    15  		_ = tcp.SetKeepAlive(true)
    16  		_ = tcp.SetKeepAlivePeriod(30 * time.Second)
    17  	}
    18  }
    19  
    20  func serializesSocksAddr(metadata *C.Metadata) []byte {
    21  	buf := pool.BufferWriter{}
    22  
    23  	addrType := metadata.AddrType()
    24  	buf.PutUint8(uint8(addrType))
    25  
    26  	switch addrType {
    27  	case socks5.AtypDomainName:
    28  		buf.PutUint8(uint8(len(metadata.Host)))
    29  		buf.PutString(metadata.Host)
    30  	case socks5.AtypIPv4, socks5.AtypIPv6:
    31  		buf.PutSlice(metadata.DstIP.AsSlice())
    32  	}
    33  
    34  	buf.PutUint16be(uint16(metadata.DstPort))
    35  	return buf.Bytes()
    36  }
    37  
    38  func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
    39  	host, port, err := net.SplitHostPort(address)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	ip, err := resolver.ResolveProxyServerHost(host)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
    49  }
    50  
    51  func safeConnClose(c net.Conn, err error) {
    52  	if err != nil && c != nil {
    53  		_ = c.Close()
    54  	}
    55  }