Unable to connect to php socket(err_connection_refused) - php

Last time I've been recreating websocket protocol on my server. But recently when I connected to my server there was an error -err_connection_refused. I started analyzing packets that browser sends. I started with websocket, unfortunately there weren't any packets(sent to the server). Then I went a little bit lower to the http protocol and there weren't any captured packets too!!! Then I decided to check tcp protocol and noticed that there actually were a few packets, but server somehow didn't respond to them. Here's my php socket code:
function go(){
echo "GO() ... <br />\r\n";
echo "socket_create ...";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket < 0){
echo "Error: ".socket_strerror(socket_last_error())."<br />\r\n";
exit();
} else {
echo "OK <br />\r\n";
}
echo "socket_bind ...";
$bind = socket_bind($socket, '54.37.233.12', 9080); if($bind < 0){
echo "Error: ".socket_strerror(socket_last_error())."<br />\r\n";
exit();
}else{
echo "OK <br />\r\n";
}
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
echo "Listening socket... ";
$listen = socket_listen($socket, 100);
if($listen < 0){
echo "Error: ".socket_strerror(socket_last_error())."<br />\r\n";
exit();
}else{
echo "OK <br />\r\n";
}
$socket_arr = array();
socket_set_nonblock($socket);
while(true){
$accept = #socket_accept($socket);
if($accept != false){
echo "OK <br />\r\n";
echo "Client \"".$accept."\" has connected<br />\r\n";
$res = array("socket" => $accept, "handshake" => false);
array_push($socket_arr, $res);
Some code below(that you don't need)...
}
}
}
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
ignore_user_abort(true);
$socket = go();
P.S There were no errors in console and all ports are already opened

Related

How to check whether the connection is establish or not on FIX api?

I just want to establish connection with FIX api using host and port (which i gave by puchasing connection) and if i connect successfuly then i send a logon request to login on FIX api and then i rececived server response but the problem is i receive a empty(0) respose
MY CODE IS
<?php
/*
Template Name: connection
*/
?>
<?php
error_reporting(E_ALL);
date_default_timezone_set('Asia/Kolkata');
echo date("YmdH:i:s.ms");
$date =date("Ymd-H:i:s.ms");
/* Get the port . */
$service_port = "(some port no.)";
/* Get the IP address for the target host. */
$address = gethostbyname('.....some host name....');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.............<br>";
}
echo "................Attempting to connect to '$address' on port '$service_port'......<br>";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK............,<br>";
}
$in = "8=FIX.4.3\0019=149\00135=A\00134=1\00149="SenderCompID"\00152=".$date."\00156="TargetCompID"\00198=0\001108=60\001141=Y\001553="Username"\001554="Password"\00110=161\001";
$out = '';
echo "Sending request...";
socket_write($socket, $in, strlen($in));
echo "OK...........<br>";
echo "<br> ------------------Reading response:-------------------<br>";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
echo "Read $bytes bytes from socket_recv(). Closing socket...<br>";
} else {
echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);
echo $buf . "Message End <br>";
echo "OK.\n\n";
?>
The output I am getting in my XAMPP server page in Wordpress is:
2020031910:11:35.0335OK.............
................Attempting to connect to '(some Host IP Adress)' on port '(port no)'......
OK............,
Sending request...OK...........
------------------Reading response:-------------------
Read 0 bytes from socket_recv(). Closing socket...
Message End
OK.
I would like to ask some things:
1) Is this occuring because of my code or configuration ?
2) Or is this because of issue at FIX server ?
3) Is there any other method to connect with FIX server?
It could be you need to change the line
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
echo "Read $bytes bytes from socket_recv(). Closing socket...<br>";
} else {
echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
Why don’t you try using https://www.quickfixj.org/ it is industry standard.

Close PHP TCP Socket after 5 sec

I created a PHP script which connects to a TCP Socket server, sends a identification, then will receive constant updates. (It connects to my thermostat) However currently PHP will keep the socket open until it's closed by my thermostat. How can I automaticly close the socket from the PHP script after 5 seconds?
<?php
//Port and IP
$service_port = ('5000');
$address = ('10.0.0.14');
// Create a TCP/IP socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "<br />";
} else {
echo "OK.<br />";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.<br />Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "<br />";
} else {
echo "OK.<br />";
}
$in .= "{ \"action\": \"identify\", \"options\": {\"core\": 0,\"receiver\": 1,\"config\": 0,\"forward\": 0}, \"media\": \"all\"}";
$out = '';
//Send Message
socket_write($socket, $in, strlen($in));
//Reply
echo "Reading response:<br /><br />";
while ($out = socket_read($socket, 2048)) {
echo $out."<br /><br />";
}
socket_close($socket);
?>
`
Sockets are open, while an exception is not occur. You have to set a socket read timeout value before you starts to read it.
socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));
If you dont do this, while loop will wait until forever for a signal.

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.

Can't Create Client Server Socket Program in Php

I am working on Client Server Socket Program for chat like application, but it is giving following error message
Warning: socket_bind(): unable to bind address [98]: Address already in use.... Could not bind to address on line 15
I have seen various tutorials, but i want Server to listen to client request continuously. I have seen port number it is open also but still the same message. I am stuck at this point for several days could not get proper solutions. Please help to solve it thanks.....
Server.php:
<?php
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();
$address = 'XXX.XX.XX.XXX';
$port = 15213;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
Client.php
<?php
error_reporting(E_ALL);
echo "<h2>TCP/IP Connection</h2>\n";
/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');
/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>
In both php files you create a Socket on the same port. That is the problem.
The Server has to create the Socket while the client has to use the Socket (not creating it, too)
Two applications can not create the same socket and listen on the same port.
EDIT:
I have tested your script with xampp at localhost. so IP was 127.0.0.1. The Server listened properly on port 15213 and the client connected properly on this port.
That the port was open i saw with the xampp controll panel.
If you use your scripts like you posted here, then you have to replace in Server.php
$address = 'XXX.XX.XX.XXX';
with
$address = '127.0.0.1';
and in Client.php
$address = gethostbyname('www.example.com');
with
$address = gethostbyname('localhost');
or
$address = '127.0.0.1';

Using PHP broadcast to detect Server IP address

I want to do something like this article:
broadcast to detect Server IP address
and transfer to PHP, does it possible?
The reason is I want to send broadcast socket to server, and the server will return message then I can determine the message is what I want or not to detect the true IP of the message sender.
The code is like:
<?php
error_reporting(E_ALL);
$address = "255.255.255.255";
$port = 10000;
/* Create a udp socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "<br/>";
} else {
echo "socket successfully created.<br/>";
}
echo "Attempting to connect to '$address' on port '$port'..."."<br/>";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "<br/>";
} else {
echo "successfully connected to $address."."<br/>";
}
$i="theMessage";
echo "Sending $i to server."."<br/>";
socket_write($socket, $i, strlen($i));
$input = socket_read($socket, 512);
echo "Response from server is: $input"."<br/>";
$ip="";
if($input=="I want")
$ip=socket_send_from_the_IP; // just psuedocode
echo "Closing socket...";
socket_close($socket);
?>
Or is the direction of my question wrong?
I also think that I should use httprequest?
Any answer appreciated.

Categories