Golang TCP转发到指定地址

Golang TCP转发到指定地址

第二个版本,设置指定ip地址

代码

// tcpForward
package main

import (
    "fmt"
    "net"
    "os"
)

func TcpForward(port int, forAddr string) {
    lisPort := fmt.Sprint(":", port)
    listen, err := net.Listen("tcp", lisPort)
    if err != nil {
        fmt.Printf("fault to listen,err: %s", err.Error())
        os.Exit(1)
    }
    defer listen.Close()
    fmt.Printf("listenning now!")
    for {
        fromConn, err := listen.Accept()
        if err != nil {
            fmt.Printf("fault,err: %s", err.Error())
            fromConn.Close()
            continue
        }
        //fmt.Printf(fromConn.LocalAddr(), " ", fromConn.RemoteAddr(), " ", fromConn)
        //buf := make([]byte, 2048)
        //fromConn.Read(buf)
        //fmt.Printf(string(buf))

        if forAddr == "" {
            go toDial(fromConn)
        } else {
            go forDial(fromConn, forAddr)
        }
    }

}

func forDial(fromConn net.Conn, forAddr string) {
    toConn, err := net.Dial("tcp", forAddr)
    if err != nil {
        fmt.Printf("fault,err: %s", err.Error())
        toConn.Close()
        return
    }
    fmt.Printf("%s to %s", fromConn.LocalAddr().String(), toConn.RemoteAddr().String())
    go copy(fromConn, toConn, 512)
    go copy(toConn, fromConn, 512)
}

func toDial(fromConn net.Conn) {
    toAddr := fromConn.RemoteAddr()
    toConn, err := net.Dial("tcp", toAddr.String())
    if err != nil {
        fmt.Printf("fault,err: %s", err.Error())
        toConn.Close()
        return
    }
    fmt.Printf("%s to %s", fromConn.LocalAddr().String(), toConn.RemoteAddr().String())
    go copy(fromConn, toConn, 512)
    go copy(toConn, fromConn, 512)
}

func copy(f, t net.Conn, n int) {
    defer f.Close()
    defer t.Close()

    var buf = make([]byte, n)

    for {
        count, err := f.Read(buf)
        if err != nil {
            fmt.Printf("fault,err: %s", err.Error())
            break
        }

        count, err = t.Write(buf[:count])
        if err != nil {
            fmt.Printf("fault,err: %s", err.Error())
            break
        }
    }
}

问题总结

没有进行大量测试,未对详细错误进行错误处理,程序容易崩溃

posted @ 2019-06-17 20:18  波士地盘  阅读(1063)  评论(0编辑  收藏  举报