Golang Implementing a TCP forwarding Agent

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
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 specifies the port the service listens to") 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 specifies the backend IP and port, multiple uses ', ' separated ') Flag. Parse () Truelist = strings. Split (List, ",") If Len (truelist) <= 0 {fmt. PRINTLN ("Backend IP and port cannot be empty, or invalid") 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 ("Establish connection error:%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 ("Connection%v failed:%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 ("Send data to%v failed:%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 ("Failed to receive data from%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}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.