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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
package main
import (
"fmt"
"io"
"net"
"net/http"
"os"
"time"
)
var targetIP string
const waitSecond = 120 // 等待时间
var (
tranNum int // 总转发数
httpNum int // 总接收http数
)
func main() {
go httpServer()
proxyStart(22, 22)
}
// 每次从光标开始处输出
func beginEcho(str string) {
fmt.Printf("\r") // 光标回到开始处
fmt.Printf("[%s] %s ", time.Now().Format("2006-01-02 15:04:05.000"), str)
}
func echo(str string) {
fmt.Printf("[%s] %s \n", time.Now().Format("2006-01-02 15:04:05.000"), str)
}
func httpServer() {
mux := http.NewServeMux()
mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {
ip := r.FormValue("ip")
result := "success"
address := net.ParseIP(ip)
if address != nil {
httpNum += 1
targetIP = address.String()
result = fmt.Sprintf("(%d)收到请求,注册目标IP为:%s", httpNum, targetIP)
} else {
result = ip + " IP地址格式不正确!"
}
beginEcho(result)
w.Write([]byte(result + "\n"))
})
echo("http listen:8888")
err := http.ListenAndServe(":8888", mux)
if err != nil {
fmt.Printf("http listen fail :%v \n", err)
os.Exit(2)
}
}
func proxyStart(fromPort, toPort int) {
proxyaddr := fmt.Sprintf(":%d", fromPort)
proxyListener, err := net.Listen("tcp", proxyaddr)
if err != nil {
fmt.Printf("Unable to listen on: %s, error: %s\n\n", proxyaddr, err.Error())
os.Exit(1)
}
echo("tcp listen" + proxyaddr)
defer proxyListener.Close()
for {
proxyConn, err := proxyListener.Accept()
if err != nil {
fmt.Printf("Unable to accept a request, error: %s\n", err.Error())
continue
}
buffer := make([]byte, 1024)
n, err := proxyConn.Read(buffer)
if err != nil {
if err != io.EOF {
fmt.Printf("Unable to read from input, error: %s\n", err.Error())
}
continue
}
if len(targetIP) == 0 {
echo("收到请求,等待目标主机注册:8888/register?ip=")
for i := 1; i <= waitSecond; i++ {
beginEcho(fmt.Sprintf("wait %d second ... ", i))
time.Sleep(time.Second)
if len(targetIP) > 0 {
echo("目录IP注册成功")
break
}
}
}
// 过了指定时间,没收到请求,关闭此次连接
if len(targetIP) == 0 {
proxyConn.Close()
continue
}
targetAddr := fmt.Sprintf("%s:%d", targetIP, toPort)
targetConn, err := net.Dial("tcp", targetAddr)
if err != nil {
fmt.Printf("Unable to connect to: %s, error: %s\n\n", targetAddr, err.Error())
proxyConn.Close()
continue
}
tranNum += 1
beginEcho(fmt.Sprintf("(%d)接收到[%s]请求,转发到 %s", tranNum, proxyConn.RemoteAddr(), targetAddr))
n, err = targetConn.Write(buffer[:n])
if err != nil {
fmt.Printf("Unable to write to output, error: %s\n", err.Error())
proxyConn.Close()
targetConn.Close()
continue
}
go io.Copy(proxyConn, targetConn)
go io.Copy(targetConn, proxyConn)
}
}
|