透明代理(二)
二 、代理实现
监听TCP链接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19var bindAddr=":3128"
laddr, err := net.ResolveTCPAddr("tcp", bindAddr)
if err != nil {
log.Println(err)
return
}
tl, err := net.ListenTCP("tcp", laddr)
if err != nil {
log.Println(err)
return
}
for {
conn, err := tl.AcceptTCP()
if err != nil {
log.Println(err)
return
}
go handleConnection(conn)
}建立远程链接+传输数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20func handleConnection(conn *net.TCPConn) {
defer func() { _ = conn.Close() }()
originAddr, nConn, err := GetOriginalDst(conn)
if err != nil {
_ = conn.Close()
return
}
defer func() { _ = nConn.Close() }()
log.Println(originAddr.String())
rconn, err := dialWithUpStream(&originAddr)
if err != nil {
log.Println(err)
return
}
defer func() { _ = rconn.Close() }()
go func() {
_, _ = io.Copy(rconn, nConn)
}()
_, _ = io.Copy(nConn, rconn)
}