github.com/igoogolx/clash@v1.19.8/adapter/outbound/util.go (about)

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