golang 实现tcp转发代理的方法

时间:2022-08-25 11:57:44

我就废话不多说了,直接上代码吧:

?
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
package main
 
import (
    "flag"
    "fmt"
    "io"
    "net"
    "os"
    "strings"
    "sync"
)
 
var lock sync.Mutex
var trueList []string
var ip string
var list string
 
func main() {
    flag.StringVar(&ip, "l", ":9897", "-l=0.0.0.0:9897 指定服务监听的端口")
    flag.StringVar(&list, "d", "127.0.0.1:1789,127.0.0.1:1788", "-d=127.0.0.1:1789,127.0.0.1:1788 指定后端的IP和端口,多个用','隔开")
    flag.Parse()
    trueList = strings.Split(list, ",")
    if len(trueList) <= 0 {
        fmt.Println("后端IP和端口不能空,或者无效")
        os.Exit(1)
    }
    server()
}
 
func server() {
    lis, err := net.Listen("tcp", ip)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer lis.Close()
    for {
        conn, err := lis.Accept()
        if err != nil {
            fmt.Println("建立连接错误:%v\n", err)
            continue
        }
        fmt.Println(conn.RemoteAddr(), conn.LocalAddr())
        go handle(conn)
    }
}
 
func handle(sconn net.Conn) {
    defer sconn.Close()
    ip, ok := getIP()
    if !ok {
        return
    }
    dconn, err := net.Dial("tcp", ip)
    if err != nil {
        fmt.Printf("连接%v失败:%v\n", ip, err)
        return
    }
    ExitChan := make(chan bool, 1)
    go func(sconn net.Conn, dconn net.Conn, Exit chan bool) {
        _, err := io.Copy(dconn, sconn)
        fmt.Printf("往%v发送数据失败:%v\n", ip, err)
        ExitChan <- true
    }(sconn, dconn, ExitChan)
    go func(sconn net.Conn, dconn net.Conn, Exit chan bool) {
        _, err := io.Copy(sconn, dconn)
        fmt.Printf("从%v接收数据失败:%v\n", ip, err)
        ExitChan <- true
    }(sconn, dconn, ExitChan)
    <-ExitChan
    dconn.Close()
}
 
func getIP() (string, bool) {
    lock.Lock()
    defer lock.Unlock()
 
    if len(trueList) < 1 {
        return "", false
    }
    ip := trueList[0]
    trueList = append(trueList[1:], ip)
    return ip, true
}

以上这篇golang 实现tcp转发代理的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/fyxichen/article/details/51505542