Skip to content

Instantly share code, notes, and snippets.

@mihalicyn
Created August 12, 2017 12:02
Show Gist options
  • Save mihalicyn/533273e0d8b23de33aaf7f2cf0973d88 to your computer and use it in GitHub Desktop.
Save mihalicyn/533273e0d8b23de33aaf7f2cf0973d88 to your computer and use it in GitHub Desktop.
<?php
error_reporting(E_ALL);
echo "TCP/IP Connection\n";
$port = 23;
$address = gethostbyname('towel.blinkenlights.nl');
//$logfile = 'socket.log';
//unlink($logfile);
function wlog($msg) {
//global $logfile;
//file_put_contents($logfile, $msg, FILE_APPEND | LOCK_EX);
echo $msg;
}
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
wlog("socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n");
} else {
wlog("OK.\n");
}
//socket_set_nonblock($socket);
//use blocking mode with recv timeout 10 seconds
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=> 10, 'usec'=> 0));
wlog("Attempting to connect to '$address' on port '$port'...");
$result = socket_connect($socket, $address, $port);
if ($result === false) {
wlog("socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n");
} else {
wlog("OK.\n");
}
//if you want to use nonblock mode you need to set that before socket_connect call ;)
//socket_set_nonblock($socket);
/*
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: php.net\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
wlog("Sending HTTP HEAD request...");
socket_write($socket, $in, strlen($in));
wlog("OK.\n");
*/
wlog("Reading response:\n\n");
$data = 'This is my buffer.';
$buf = '';
//while (/*false !==*/ ($bytes = socket_recv($socket, $buf, 1024, MSG_WAITALL))) {
while (($buf = socket_read($socket, 1024))) {
$bytes = strlen($buf);
wlog("Read [$buf] $bytes bytes from socket_recv().\n");
$data .= $buf;
//flush();
//echo "Read $bytes bytes";
}
wlog("socket_recv() cycle finished; reason: " . socket_strerror(socket_last_error($socket)) . "\n");
socket_close($socket);
wlog($data . "\n");
wlog("OK.\n\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment