github.com/chwjbn/xclash@v0.2.0/adapter/outbound/util.go (about) 1 package outbound 2 3 import ( 4 "bytes" 5 "net" 6 "strconv" 7 "time" 8 9 "github.com/chwjbn/xclash/component/resolver" 10 C "github.com/chwjbn/xclash/constant" 11 "github.com/chwjbn/xclash/transport/socks5" 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 var buf [][]byte 23 aType := uint8(metadata.AddrType) 24 p, _ := strconv.ParseUint(metadata.DstPort, 10, 16) 25 port := []byte{uint8(p >> 8), uint8(p & 0xff)} 26 switch metadata.AddrType { 27 case socks5.AtypDomainName: 28 len := uint8(len(metadata.Host)) 29 host := []byte(metadata.Host) 30 buf = [][]byte{{aType, len}, host, port} 31 case socks5.AtypIPv4: 32 host := metadata.DstIP.To4() 33 buf = [][]byte{{aType}, host, port} 34 case socks5.AtypIPv6: 35 host := metadata.DstIP.To16() 36 buf = [][]byte{{aType}, host, port} 37 } 38 return bytes.Join(buf, nil) 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 }