Go 实现端口映射

Go 实现端口映射

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
        "io"
        "net"
)

func main() {
        localIP, localPort := net.ParseIP("0.0.0.0"), 80
        remoteIP, remotePort := net.ParseIP("10.0.2.2"), 8080
        localTCP, err := net.ListenTCP("tcp", &net.TCPAddr{IP: localIP, Port: localPort})
        if err != nil {
                return
        }

        for {
                conn, err := localTCP.Accept()
                if err != nil {
                        return
                }
                NewPortMap(remoteIP, remotePort, conn)
        }
}

func NewPortMap(remoteIP net.IP, remotePort int, conn net.Conn) {
        remoteTCP, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: remoteIP, Port: remotePort})
        if err != nil {
                panic(err)
                return
        }
        go func() {
                io.Copy(remoteTCP, conn)
        }()
        go func() {
                io.Copy(conn, remoteTCP)
        }()
}
Licensed under CC BY-NC-SA 4.0
最后更新于 Sep 14, 2023 15:44 +0800
使用 Hugo 构建
主题 StackJimmy 设计