Open asynchronous sockets in PHP - php

I am writing a port scanner in PHP that supports small ranges (e.g., ports 21-25). The ports and IP to be scanned are sent to the server via AJAX, and then PHP attempts to open a socket on each of the ports. If it succeeds, the port is open, if it times out, the port is closed.
Currently, despite sending all of the AJAX requests at the same time for ports 21-25, each socket is only opened after the last one closes. So, port 21 is checked, the socket is closed, and then port 22 is checked, and so on. What I want is for all ports to be checked concurrently, so I'd be opening several sockets at once.
I've tried:
$fp = #fsockopen($ip,$port,$errno,$errstr,2);
socket_set_nonblock($fp);
But this doesn't work, as I'm setting non-block AFTER the socket has already been opened and is waiting for a response. Is what I'm trying to do possible in PHP?

Use different functions: socket_create() and socket_connect() instead of fsockopen(). This works:
$socks = array();
for ($port = 21; $port <= 25; $port++) {
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($sock);
#socket_connect($sock, 'localhost', $port);
$socks[$port] = $sock;
}
$startTime = microtime(true);
while ($socks && microtime(true) - $startTime < 3) {
$null = null;
$write = $socks;
socket_select($null, $write, $null, 1);
foreach ($write as $port => $sock) {
$desc = "$port/tcp";
$errno = socket_get_option($sock, SOL_SOCKET, SO_ERROR);
if ($errno == 0) {
echo "$desc open\n";
} elseif ($errno == SOCKET_ECONNREFUSED) {
echo "$desc closed\n";
} elseif ($errno == SOCKET_ETIMEDOUT) {
echo "$desc filtered\n";
} else {
$errmsg = socket_strerror($errno);
echo "$desc error $errmsg\n";
}
unset($socks[$port]);
socket_close($sock);
}
}
foreach ($socks as $port => $sock) {
$desc = "$port/tcp";
echo "$desc filtered\n";
socket_close($sock);
}

Related

fsockopen only working to check port 80 and 8000 (no other ports)

I'm trying to use fsockopen as a port checker to see if a specific port is open on an IP address, but it only seems to be working on Ports 80 and 8000. For any other port, it returns that the port is closed even when it is open. I was wondering how I could possibly fix this?
$server_ip= $_POST['server'];
$port = $_POST['port'];
$server_ip = gethostbyname($server_ip);
$status = array();
if (empty($_POST["server"]) || empty($_POST['port']) || !filter_var($server_ip, FILTER_VALIDATE_IP) )
{
echo "some html code";
}
elseif (!(is_numeric($port)))
{
echo "some other html code";
}
else
{
if($pf = #fsockopen($_POST['server'], $port, $err, $err_string, 1)) {
$status = true;
fclose($pf);
} else {
$status = false;
}
Output code here..
}

PHP fsocketopen - returns false when port is open

I made this code which is supposed to show whether the program running on the specified port is running.
Now the problem is that it shows "Offline" when my port is clearly open. It however does show online for Google on port 80. What am I doing wrong?
$server = '77.251.97.234';
$port = 43594;
$timeOut = 1;
if ($socket = #fsockopen($server, $port, $errorNo, $errorStr, $timeOut)) {
echo '<span style="color:green;">Online</span>';
} else {
echo '<span style="color:red;">Offline</span>';
}

PHP Socket Program hangs

I have a socket server program written in PHP and run by Fedora 21-apache, listening on a port.
<?php
set_time_limit (0);
$address = '1.2.3.4';
$port = "19000";
$con = 1;
$word = "";
$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$bind = socket_bind($sock, $address, $port) or die("Could not bind to socket\n");
socket_listen($sock);
while ($con == 1)
{
$client = socket_accept($sock);
$input = socket_read($client, 50);
if ($input == 'exit')
{
$close = socket_close($sock);
$con = 0;
}
else {
$input = trim($input) . "," . date('Y-m-d H:i:s') . "\n";
$file= "/home/xyz/data/" . "uls_" . date("Ymd_His") . ".dat";
file_put_contents($file, $input);
}
}
?>
The client is actually a device. Currently there is only one device running.
As per the documentation provided by the device,
"It acts as a TCP client and opens a TCP socket session to the Server. The
device then sends a message and disconnects the socket session. Failed connections force retries"
Now I am able to get data from this client. The problem is that after say 4-5 Hours client is not able to push data.The server socket hangs.
The netstat -taun command shows following.
tcp 0 0 1.2.3.4:19000 0.0.0.0:* LISTEN
tcp 0 0 1.2.3.4:19000 3.4.5.6:20721 ESTABLISHED
Sometimes more than one client connections could be seen.
I can confirm that the client is still running during this time. I tried to connect to this server socket through another client socket script.
The result says, client request made but server socket did not respond.
If restart the web server, and run the server script again, everyrthing works normal for sometime.
Could anyone help me identify the problem.
I ran with the same probleme, i fixed it by closing the resource built by socket_accept()
while ($con == 1)
{
$client = socket_accept($sock);
$input = socket_read($client, 50);
if ($input == 'exit')
{
$close = socket_close($sock);
$con = 0;
}
else {
$input = trim($input) . "," . date('Y-m-d H:i:s') . "\n";
$file= "/home/xyz/data/" . "uls_" . date("Ymd_His") . ".dat";
file_put_contents($file, $input);
}
// #param2 - 1 => block writing in socket ...
socket_shutdown ($client , 1) ;
socket_close ($client ) ;
}

Python socket server to PHP client socket

I'm trying to setup a socket connection between Python and PHP. Python will function as server and PHP as client. I want to start the webpage and check if thread in Python is running, so I send a variable into the socket to PHP. This works. When the page is loaded the user can click on buttons to enable or disable the thread. So these buttons send back a variable enable/disable. But I'm unable to send this data back into the socket. What can I do to get the button press data back into the socket?
import time
import socket
import logging
def socketCon():
LOG_FILENAME = "logging.out"
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.info("Started setting up the socket to php connection")
HOST = '127.0.0.1' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
logging.info("Connected to Server")
except socket.error, msg:
logging.info('Socket Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
s = None
continue
try:
s.bind(sa)
logging.info("Bind Complete")
s.listen(1)
logging.info("Now Listening to socket")
except socket.error, msg:
logging.info('Socket bind/listening Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
s.close()
s = None
continue
break
if s is None:
logging.info("could not open socket")
#try:
logging.info("Waiting on Socket to Accept")
conn, addr = s.accept()
logging.info("Connected by "+str(addr))
# Get data from the socket
#data1 = conn.recv(1024)
#logging.info("What did the user send from the Website: "+str(data1))
# Send data to socket
alarm = "Enabled"
conn.send(alarm)
logging.info("Send status to client socket: "+str(alarm))
run = True
logging.info("Waiting for user button press")
# Wait for user button press from website
while run == True:
# Get the button press from the website
data2 = conn.recv(1024)
logging.info("Recieving data: "+str(data2))
if data2 == 0:
logging.info("What did the user select from the Website: "+str(data2))
run = False
# close the socket
conn.close()
def runTest():
#while:
try:
socketCon()
except:
print "There was a problem"
socketCon()
#runTest()
PHP client:
if(isset($_SESSION['id']))
{
// Put stored session variables into local PHP variable
$uid = $_SESSION['id'];
$usname = $_SESSION['username'];
$result = "Login data: <br /> Username: ".$usname. "<br /> Id: ".$uid;
error_reporting(E_ALL);
// Allow the script to hang around waiting for connections.
set_time_limit(0);
// Turn on implicit output flushing so we see what we're getting as it comes in.
ob_implicit_flush();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
//$output="Client Logged on via website" ;
//socket_write($socket, $output, strlen ($output)) or die("Could not write output\n");
// Get the response from the server - our current telemetry
$resultLength = socket_read($socket, 1024) or die("Could not read server response\n");
$result4 = $resultLength;
if($result4 === "Enabled")
{
echo "Alarm is Running";
$disabled1 = "disabled='disabled'";
$disabled2 = "";
}
elseif($result4 === "Disabled")
{
echo "Alarm is not running";
$disabled1 = "";
$disabled2 = "disabled='disabled'";
}
// close the socket
socket_close($socket);
}
else
{
$result = "You are not logged in yet";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $usname ;?> - Alarm Enable/Disable</title>
</head>
<body>
<br>
<?php
echo $result;
?>
<br>
<?php
echo $result2;
?>
<br>
<form id="form" action="user.php" method="post" enctype="multipart/form-data">
<input type='submit' name='submit1' value='Enable Alarm' <?php echo $disabled1; ?> />
<input type='submit' name='submit2' value='Disable Alarm' <?php echo $disabled2; ?> />
</form>
<article>
<?php
if (isset($_POST[submit1]))
{
/*// Allow the script to hang around waiting for connections.
set_time_limit(0);
// Turn on implicit output flushing so we see what we're getting as it comes in.
ob_implicit_flush();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
*/
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
$input="Enable";
socket_write($socket, $input, strlen ($input)) or die("Could not write input\n");
echo "Send Enable back into socket to the Server";
// close the socket
socket_close($socket);
// Now direct to user feed
header("Location: logout.php");
}
if (isset($_POST[submit2]))
{
/*// Allow the script to hang around waiting for connections.
set_time_limit(0);
// Turn on implicit output flushing so we see what we're getting as it comes in.
ob_implicit_flush();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
*/
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
$input="Disable";
socket_write($socket, $input, strlen ($input)) or die("Could not write input\n");
echo "Send Disable back into socket to the Server";
// close the socket
socket_close($socket);
// Now direct to user feed
header("Location: logout.php");
}
?>
</article>
<br>
Logout
</body>
</html>
Ok I foudn the solution. I need to define a loop to get the s.accept() so that when the client want's to connect to the server it gets the new adrr values.
To solve this problem you will need to put s.accept() in a loop. This will make sure the connection remains established.

PHP socket server closes when connect client to server

I'm coding a php socket server script which is running on ubuntu.
It works well, clients can connect/disconnect to this server.
But the server is shutting down silently when a client connect to this server that didn't have any client connected for a long time.
I setted up timeout to 0 (unlimited) but the server is stoping without any errors or messages... like this.
root#exfl:/home/projectap/sec/server_core# php socket_server.php
[exfl.kr] Starting AbsolutePitch socket server...
[2014.06.21 16:50:58] Server is listening. PID: 6442
[2014.06.21 17:28:48] Client [192.168.0.1:8795] connected to the server.
root#exfl:/home/projectap/sec/server_core#
I coded for this server like this.
<?php
set_time_limit(0);
error_reporting(E_ALL);
ini_set("memory_limit","2048M");
ini_set("max_execution_time", "0");
if(posix_getpid() == true) {
echo "[exfl.kr] Starting AbsolutePitch socket server...\n";
} else {
echo getTimeToStr()."Server is already running.\n";
}
$cSock = array();
$socketsInformation = array();
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$bind = socket_bind($socket, "0.0.0.0", "24180");
$listen = socket_listen($socket, 5);
echo getTimeToStr()."Server is listening. PID: ".posix_getpid()."\n";
while(true) {
$sockArr = array_merge(array($socket), $cSock);
if(socket_select($sockArr, $tWrite = null, $tExcept = null, null) > 0) {
foreach($sockArr as $sock){
if($sock == $socket){
$tSock = socket_accept($socket);
socket_getpeername($tSock, $sockIp, $sockPort);
array_push($cSock, $tSock);
array_push($socketsInformation, array("SOCKETINDEX"=>(count($cSock)-1), "IP"=>$sockIp, "USERID"=>"", "STATUS"=>"", "AUTH"=>false));
echo getTimeToStr()."Client [".$sockIp.":".$sockPort."] connected to the server.\n";
} else {
...
}
}
}
}
echo getTimeToStr()."Server closed.\n";
...
?>
When the server stops suddenly, it isn't outputing a "Server closed" message..
Please help.
Sorry for my bad English.
You may want to try socket_set_options() with SO_KEEPALIVE. To know more about your options use the socket_get_options page:
https://www.php.net/manual/en/function.socket-get-option.php
To know more about the usage of socket_set_options() use:
https://www.php.net/manual/en/function.socket-set-option.php

Categories