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