golang 實現tcp轉送 Proxy

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport ("flag""fmt""io""net""os""strings""sync")var lock sync.Mutexvar trueList []stringvar ip stringvar list stringfunc 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)<-ExitChandconn.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}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.