利用 Socat 实现单端口 中继(中转/端口转发)加速

原文:https://www.xxkwz.cn/2363.html

使用场景:服务器之间的中转。
优点:支持 TCP/UDP 转发。
缺点:不支持端口段(多个端口需要开启多个转发)

Socat安装

  • Centos 系统:yum install -y socat
  • Debian/Ubuntu 系统:apt-get update apt-get install -y socat

Socat使用

  • 转发TCP
nohup socat TCP4-LISTEN:本地端口,reuseaddr,fork TCP4:目标IP/域名:端口 >> socat.log 2>&1 &

 

  • 转发UDP
nohup socat UDP4-LISTEN:本地端口,reuseaddr,fork TCP4:目标IP/域名:端口 >> socat.log 2>&1 &

 

nohup指的是 后台运行。
TCP4-LISTEN:2333 指的是 监听ipv4的端口,也就是 转发的端口,后面Shadowsocks链接中继时填写的 端口,中继服务器。
fork TCP4:233.233.233.233:6666 指的是 被转发的 IP 和 端口,也就是你要中继的服务器的 IP 和 端口,被中继的服务器。
/root/socat.log 2>&1 & 指的是 转发日志记录。

停止转发

ps -ef | grep socat
#输入上面的命令找到socat程序的PID,然后用下面的命令KILL掉这个PID进程(PID是个数字,自己替换下面的"pid")。
kill -9 pid

Socat卸载

Centos系统:

yum remove socat

Debian/Ubuntu系统:

sudo apt-get remove socat
sudo apt-get autoremove

防火墙设置

如果你设置后无法链接,那么多半是防火墙 阻拦了,只要开放端口 就行了。以上面的 示例的中继端口 2333 为例。

iptables -I INPUT -p tcp --dport 2333 -j ACCEPT
iptables -I INPUT -p udp --dport 2333 -j ACCEPT
  • 保存防火墙service iptables save 或 /etc/init.d/iptables save
  • 重启防火墙service iptables restart 或 /etc/init.d/iptables restart

开机启动

Centos系统:

chmod +x /etc/rc.d/rc.local
vi /etc/rc.d/rc.local

Ubuntu/Debian系统:

chmod +x /etc/rc.local
vi /etc/rc.local

输入 I 键 进入编辑模式(如果没反应请看上面的教程安装 vim),然后在打开的文件中的 exit 0 代码前面插入你的 socat 命令代码(就是上面 nohup socat…的代码)。