欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

golang 实现tcp转发代理的方法

程序员文章站 2022-11-16 12:31:20
我就废话不多说了,直接上代码吧: package main import ( "flag" "fmt" "io" "net" "os"...

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

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转发代理的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。