Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to listening netcat using PHP

Tags:

php

eof

netcat

I have a netcat server, running from command line:

netcat -l -q0 -p 9999 -c "tesseract stdin stdout -l spa"

I can connect to this server using netcat client:

cat /tmp/autogenerado.jpg | netcat 127.0.0.1 9999

So, I send a jpeg file to another server, and receive the OCR'ed data in client.

I want to do this in PHP:

$fp = fsockopen("tcp://127.0.0.1:9999", $errno, $errstr); 

if (!$fp) {
    echo "{$errno}: {$errstr}\n";
    die();
}

fwrite($fp, $jpeg);

$contents = stream_get_contents($fp);

fclose($fp);

return $contents;

But the script hangs on stream_get_contents. I think it is because the netcat server doesn't know when the PHP client has finished sending data.

Is it possible to send an EOF ?

like image 745
Augusto Beiro Avatar asked Dec 01 '25 20:12

Augusto Beiro


2 Answers

You need to shutdown the socket for writing, something like this:

<?php
$stream = stream_socket_client("tcp://whatever:9999", $errno, $errstr);

if (!$stream) {
    echo "{$errno}: {$errstr}\n";
    die();
}

fwrite($stream, $jpeg);

stream_socket_shutdown($stream, STREAM_SHUT_WR); /* This is the important line */

$contents = stream_get_contents($stream);

fclose($stream);

return $contents;
?>
like image 174
Joe Watkins Avatar answered Dec 04 '25 10:12

Joe Watkins


For reference, final working code is:

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($sock, "10.187.252.35", 9999);
socket_send($sock,$bdata,strlen($bdata),MSG_EOR):
socket_shutdown ($sock,1);
while ($out = socket_read($sock, 2048)) {
    echo $out;
}
socket_close($sock);
like image 23
Augusto Beiro Avatar answered Dec 04 '25 10:12

Augusto Beiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!