GO TCP代理(可代理SQLSERVER\MYSQL\ORCALE)

用nginx代理不知道为什么内网能用,外网用不了,改用go写个代理临时用下,直接上代码

 

package main

import (
	"fmt"
	"io"
	"log"
	"net"
)

var addr string = "0.0.0.0:51415"  //代理服务端口
var dest_addr string = "192.168.2.120:1433"  //目标地址

func main() {
	defer func() {
		if err := recover(); err != nil {
			log.Println("捕获异常并恢复,异常是:", err)
		}
	}()

	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Printf("Failed to start listener: %s", err)
		return
	}
	defer listener.Close()

	fmt.Println("Proxy server is listening on ", addr)

	for {
		client, err := listener.Accept()
		if err != nil {
			log.Printf("Failed to accept client connection: %s", err)
			continue
		}

		go handleClient(client, dest_addr) 
	}
}

func handleClient(client net.Conn, remoteAddr string) {
	remote, err := net.Dial("tcp", remoteAddr)
	if err != nil {
		log.Printf("Failed to connect to remote server: %s", err)
		client.Close()
		return
	}

	go func() {

		_, err := io.Copy(remote, client)
		if err != nil {
			log.Printf("Error copying from client to remote: %s", err)
		}
	}()

	_, err = io.Copy(client, remote)
	if err != nil {
		log.Printf("Error copying from remote to client: %s", err)
	}

	remote.Close()
	client.Close()
}

  

posted @ 2023-12-13 20:37  wsh3166Sir  阅读(27)  评论(0编辑  收藏  举报