-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaddr.go
More file actions
64 lines (60 loc) · 1.16 KB
/
Copy pathaddr.go
File metadata and controls
64 lines (60 loc) · 1.16 KB
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
package proxy
import (
"fmt"
"net"
"strconv"
)
const (
IPv4 = 0x01
FQDN = 0x03
)
func ReadAddr(conn net.Conn) (addr string, err error) {
var buf [256]byte
_, err = conn.Read(buf[:1])
if err != nil {
return
}
switch buf[0] {
case IPv4:
_, err = conn.Read(buf[:6])
if err != nil {
return
}
port := uint16(buf[4])<<8 | uint16(buf[5])
addr = fmt.Sprintf("%s:%d", net.IPv4(buf[0], buf[1], buf[2], buf[3]), port)
case FQDN:
_, err = conn.Read(buf[:1])
if err != nil {
return
}
alen := int(buf[0])
_, err = conn.Read(buf[:alen+2])
if err != nil {
return
}
port := uint16(buf[alen])<<8 | uint16(buf[alen+1])
addr = fmt.Sprintf("%s:%d", buf[:alen], port)
default:
err = fmt.Errorf("not support atyp %v", buf[0])
}
return
}
func WriteAddr(conn net.Conn, addr string) (err error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return
}
portn, err := strconv.Atoi(port)
if err != nil {
return
}
buf := make([]byte, 259)
buf[0] = 0x03
hLen := len(host)
buf[1] = byte(hLen)
copy(buf[2:2+hLen], host)
buf[2+hLen] = byte(uint16(portn) >> 8)
buf[3+hLen] = byte(portn)
_, err = conn.Write(buf[:4+hLen])
return
}