php 实现端口转发
实现端口转发的方法
在 PHP 中实现端口转发通常需要结合系统调用或扩展功能,以下是几种常见的方法:

使用 stream_socket_client 和 stream_socket_server
通过 PHP 的流函数创建客户端和服务端套接字,实现数据转发:

$localPort = 8080;
$remoteHost = 'example.com';
$remotePort = 80;
$server = stream_socket_server("tcp://0.0.0.0:$localPort");
while ($client = stream_socket_accept($server)) {
$remote = stream_socket_client("tcp://$remoteHost:$remotePort");
stream_copy_to_stream($client, $remote);
stream_copy_to_stream($remote, $client);
fclose($client);
fclose($remote);
}
使用 socket_create 函数
通过更底层的 socket 函数实现转发:
$localPort = 8080;
$remoteHost = 'example.com';
$remotePort = 80;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, '0.0.0.0', $localPort);
socket_listen($sock);
while ($client = socket_accept($sock)) {
$remote = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($remote, $remoteHost, $remotePort);
$buf = '';
while ($read = socket_read($client, 2048)) {
$buf .= $read;
socket_write($remote, $read);
}
while ($read = socket_read($remote, 2048)) {
socket_write($client, $read);
}
socket_close($client);
socket_close($remote);
}
使用系统命令调用
通过调用系统工具如 socat 或 iptables 实现:
$localPort = 8080;
$remoteHost = 'example.com';
$remotePort = 80;
// 使用 socat
exec("socat TCP-LISTEN:$localPort,fork TCP:$remoteHost:$remotePort");
// 或使用 iptables
exec("iptables -t nat -A PREROUTING -p tcp --dport $localPort -j DNAT --to-destination $remoteHost:$remotePort");
exec("iptables -t nat -A POSTROUTING -j MASQUERADE");
注意事项
- PHP 脚本需要以 root 权限运行才能绑定低端口(如 80)
- 长时间运行的脚本需要考虑内存泄漏和超时问题
- 生产环境建议使用专业的反向代理工具如 Nginx、HAProxy
- Windows 系统可能需要使用不同的命令或函数
以上方法可以根据实际需求选择适合的方案,对于高性能场景建议使用专门的代理服务器软件。






