我正在运行脚本 server.php ,我正在收听IP和PORT。我通过运行 input.php 来模拟传入的消息。
问题:我如何收听每个端口?
注意:我正在尝试捕获任何消息,无论在哪个端口上,都将通过TCP / IP协议传输到我的IP。
server.php
function writeToFile($strFilename, $strText)
{
if ($fp = @fopen($strFilename, "a+")) {
$contents = fwrite($fp, $strText . PHP_EOL);
fclose($fp);
return true;
} else {
return false;
}
}
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$bind = socket_bind($sock, $address, $port);
socket_listen($sock, 5);
while ($con == 1) {
$client = socket_accept($sock);
$input = socket_read($client, 100);
$prefix = date('Y_m_d');
$data = $prefix . '_data.txt';
writeToFile($data, $input);
if ($input == 'exit') {
socket_close($sock);
$con = 0;
}
if ($con == 1) {
$word .= $input;
}
echo $input . PHP_EOL;
socket_write($client, $input . PHP_EOL);
}
input.php
<?php
$address = "192.168.0.103";
$port = 5503;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
$fp = fsockopen($address, $port);
$bytes = fwrite($fp, $randomString);
if ($bytes == false) {
echo 'Send data: 0 Bytes';
} else {
echo 'Send data: ' . $bytes . ' Bytes';
}
fclose($fp);
exit;
答案 0 :(得分:1)
通过创建套接字来监听所有端口并不是一个好主意。更好地监控传入的SYN(同步)请求,然后绑定到该特定端口。
您可以使用tcpdump
来监控传入的请求。
tcpdump -i eth0 -s 1500 port not 22 and '(tcp-syn|tcp-ack)!=0'
您可以按port not
排除端口。确保使用正确的接口名称。
使用php函数proc_open
执行上述命令,因为tcpdump
提供连续输出。
$cmd = 'tcpdump -i eth1 -s 1500 port not 22 and "(tcp-syn|tcp-ack)!=0"';
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());
if (is_resource($process)) {
while ($s = fgets($pipes[1])) {
print $s;
//make sure $s is a SYN request then create and listen to port
flush();
}
}