PHP - монитор сокета для всех портов

1

Я запускаю скрипт 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;
Теги:
sockets

1 ответ

1

Прослушивание всех портов путем создания сокета - не очень хорошая идея. Лучше контролировать входящий запрос SYN (synchronize), а затем привязываться к этому конкретному порту.

Вы можете использовать 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();
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню