常见的端口转发技巧

常见的端口转发技巧

如果你只有一个公网IP 但是有几台服务器需要对外提供服务。可以使用以下几种方式

1. windows 下使用 netsh

​ 不用重启机器,还长记性。命令即时生效,重启系统后配置仍然存在。但是不支持UDP,XP 需要安装 IPV6 支持

  • 安装支持

    1
    netsh interface ipv6 install
  • 查看已经添加的端口映射

    1
    netsh interface portproxy show v4tov4
  • 添加端口映射支持

    1
    netsh interface portproxy add v4tov4 listenaddress=192.168.0.101 listenport=2133 connectaddress=192.168.0.251 connectport=2133

    将本机192.168.0.101 的 2133端口映射到192.168.0.251 的2133 端口

  • 删除端口

    1
    netsh interface portproxy delete v4tov4 listenaddress=192.168.0.101 listenport=2133

2. SSH 实现

https://www.ibm.com/developerworks/cn/linux/l-cn-sshforward/

##3. Nginx 实现

贴出配置

1
stream{
2
log_format proxy '{ "@timestamp": "$time_local", '
3
                         '"@fields": { '
4
                         '"remote_addr": "$remote_addr", '
5
                         '"protocol": "$protocol", '
6
                         '"status": "$status", '
7
                         '"bytes_sent": "$bytes_sent", '
8
                         '"bytes_received": "$bytes_received", '
9
                         '"session_time": "$session_time", '
10
                         '"upstream_addr": "$upstream_addr", '
11
                         '"upstream_bytes_sent": "$upstream_bytes_sent", '
12
                         '"upstream_bytes_received": "$upstream_bytes_received", '
13
                         '"upstream_connect_time": "$upstream_connect_time" } }';
14
    access_log /home/www/log/proxy.log proxy;
15
    open_log_file_cache off;
16
include /etc/nginx/stream.d/*.conf;
17
}

stream.d/proxy.conf

1
server {
2
        # 本机监听端口 8080
3
        listen                3389;
4
        # 请求抛给 stream_backend 组
5
        proxy_pass            192.168.0.101:3389;
6
}

4. socat

1
socat tcp4-listen:4342,reuseaddr,fork unix-connect:/var/run/docker.sock
2
socat TCP4-LISTEN:188,reuseaddr,fork TCP4:192.168.1.22:123

5. NC

6. iptable

iptables -t nat -I PREROUTING -i eth0 -p TCP –dport 4040 -j DNAT –to-destination :4040

7. haproxy