-
Notifications
You must be signed in to change notification settings - Fork 107
/
net.go
71 lines (64 loc) · 1.3 KB
/
net.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
59
60
61
62
63
64
65
66
67
68
69
70
71
package socks
import (
"bytes"
"fmt"
"net"
"strconv"
"time"
)
type requestBuilder struct {
bytes.Buffer
}
func (b *requestBuilder) add(data ...byte) {
_, _ = b.Write(data)
}
func (c *config) sendReceive(conn net.Conn, req []byte) (resp []byte, err error) {
if c.Timeout > 0 {
if err := conn.SetWriteDeadline(time.Now().Add(c.Timeout)); err != nil {
return nil, err
}
}
_, err = conn.Write(req)
if err != nil {
return
}
resp, err = c.readAll(conn)
return
}
func (c *config) readAll(conn net.Conn) (resp []byte, err error) {
resp = make([]byte, 1024)
if c.Timeout > 0 {
if err := conn.SetReadDeadline(time.Now().Add(c.Timeout)); err != nil {
return nil, err
}
}
n, err := conn.Read(resp)
resp = resp[:n]
return
}
func lookupIPv4(host string) (net.IP, error) {
ips, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for _, ip := range ips {
ipv4 := ip.To4()
if ipv4 == nil {
continue
}
return ipv4, nil
}
return nil, fmt.Errorf("no IPv4 address found for host: %s", host)
}
func splitHostPort(addr string) (host string, port uint16, err error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return "", 0, err
}
portInt, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return "", 0, err
}
port = uint16(portInt)
return
}