Ing. Michal Hudak
Ing. Michal Hudak

Reputation: 5622

PHP - monitor socket for all ports

I am running script server.php where I am listening to IP and PORT. I simulate incoming message by running input.php.

Question: How can I listen to every port?

Note: I am trying to catch any message, that will go via TCP/IP protocol to my IP regardless on which port.

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;

Upvotes: 1

Views: 562

Answers (1)

Harikrishnan
Harikrishnan

Reputation: 9979

Listening to all ports by creating a socket is not a good idea. Better monitor incoming SYN (synchronize) request and then bind to that particular port.

You can use tcpdump for monitoring incoming requests.

tcpdump -i eth0 -s 1500 port not 22 and '(tcp-syn|tcp-ack)!=0'

You can exclude ports by port not. Make sure to use correct interface name.

Execute above command with php function proc_open, since tcpdump gives continuous output.

 $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();
    }
}

Upvotes: 1

Related Questions