I need help with a code that I must pass from PHP to C.
The code allows to send via SOCKET an instruction to a remote device.
It works perfect for me in PHP, but I have to convert it to C. Everything is fine, except PHP's pack () function, I do not see how to replace it in C.
Basically I have to pass this:
$message = pack("H2H8H2H4H4", "a5", "00000001", "5e", "0000", "bc19");
A mesaje_in_c = ¿ ?
I would appreciate the support you can give me, thanks!
This is the PHP code:
<?php
$host = "192.168.0.140";
$port = 8081;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
print "socket_create() falló: razón: " . socket_strerror(socket_last_error()) ."\n";
} else {
print "create socket OK.\n";
}
socket_set_option(
$socket,
SOL_SOCKET, // socket level
SO_RCVTIMEO, // timeout option
array(
"sec"=>10, // Timeout in seconds
"usec"=>0 // I assume timeout in microseconds
)
);
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
if ($result === false) {
print "socket_connect() falló.\nRazón: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
print "connect to server OK.\n";
}
$message = pack("H2H8H2H4H4", "a5", "00000001", "5e", "0000", "bc19");
echo "Message To server Bin: ".$message."\n";
echo "Message dec: ";
print_r(unpack("H*", $message))."\n";
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read($socket, 1024) or die("Could not read server response\n");
print "Reply From Server Bin:".$result."\n";
$resultHex = unpack("H*", $result);
print "Reply From Server Hex:";
print_r($resultHex)."\n";
// close socket
socket_close($socket);
?>
And this is the C code to finish:
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[]){
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message , server_reply[2000];
int recv_size;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("192.168.0.140");
server.sin_family = AF_INET;
server.sin_port = htons(8081);
//Connect to remote server
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
//Send some data
message = "a5000000015e0000bc19";
// ???? message = pack("H2H8H2H4H4", "a5", "00000001", "5e", "0000", "bc19");
if( send(s , message , strlen(message) , 0) < 0)
{
puts("Send failed");
system("pause");
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
{
puts("recv failed");
}
puts("Reply received\n");
//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);
system("pause");
return 0;
}
I would appreciate the support you can give me, thanks!
Does it work?
char message[] = "\xa5\x00\x00\x00\x01\x5e\x00\x00\xbc\x19";
Related
I am trying to send a XML to a server in a TCP\IP (socket) connection.
My connection is okay. The sending part is the issue.
See below;
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$host = "xx.xxx.xx.xxx";
$port = xxxx;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
if($result === true){
echo 'connected';
}
$sendVendRequest='
<ipayMsg client="SAFEPAY" term="00001" seqNum="0" time=" '.date('Y-m-d H: i: s').' +0200">
<elecMsg ver="2.44">
<vendReq>
<ref>319155500001</ref>
<amt cur="KSh">1000</amt>
<numTokens>1</numTokens>
<meter>A12C3456789</meter>
<payType>cash</payType>
</vendReq >
</elecMsg>
</ipayMsg>';
$vendRequestXml=simplexml_load_string($sendVendRequest) or die("Error: could not create an object");
// print_r($vendRequestXml);
socket_write($socket, $sendVendRequest, strlen($sendVendRequest)) or die("Could not send data to server\n");
The sending part fails. It loads until it times out. I suspect I am sending the request wrongly.. Someone please direct me on how to achieve this.
This code works for me:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$host = "example.com";
$port = 80;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
if($result === true){
echo 'connected';
}·
$st='
<ipayMsg client="SAFEPAY" term="00001" seqNum="0" time=" '.date('Y-m-d H: i: s').' +0200">
<elecMsg ver="2.44">
<vendReq>
<ref>319155500001</ref>
<amt cur="KSh">1000</amt>
<numTokens>1</numTokens>
<meter>A12C3456789</meter>
<payType>cash</payType>
</vendReq >
</elecMsg>
</ipayMsg>';
$length = strlen($st);
while(true) {
$sent = socket_write($socket, $st, $length);
if($sent === false) {
break;
}
// Was the entire msg sent?
if($sent < $length) {
// If not, handle the leftover data.
$st = substr($st, $sent);
$length -= $sent;
} else {
break;
}
}
echo socket_read($socket, 8192);
Can you telenet to that port?
I have socket client which connects to server and which wait for datas to be sent by this server.
It works fine but, when server has a disconnection, it has to be detected by socket client in order to try a reconnection.
Client socket code :
$co = false;
while (!$co) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create()error : " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK 1.\n";
}
echo "Try connection '$address' on port '$service_port'... \n";
$result = socket_connect($socket, $address, $service_port);
if ($socket === false) {
echo "socket_connect() error : ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
echo "OK 2.\n";
$co = true;
}
}
while (true) {
echo 'read' . PHP_EOL;
socket_clear_error($socket);
$out = socket_read($socket, 2048);
$socket_last_error = socket_last_error($socket);
$strErr = socket_strerror($socket_last_error) . ' ' . $socket_last_error;
echo("socket_last_error : " . $strErr);
var_dump($out);
}
Problem is when client socket is correctly connected to server, there's socket_last_error with value 'Resource temporarily unavailable 11' and 'socket_read' function return false when server doesn't send data.
But when server is deconnected, there's socket_last_error with value 'Success 0' and 'read' function return ''
PHP doc says :
socket_read() returns data as string on success, or FALSE on error (including case where remote host has closed connection).
So functions results are unexpected and I would like to know what's the right method to detect a server disconnection in order to try a new connection?
Thanks in advance for your answers.
I checked
php sockets read json array from java server
Sending configuration data to websocket
and spent all day on finding the solution for the following problem.
I have Client.php
<?php
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
//Connect socket to remote server
if(!socket_connect($sock , '127.0.0.1', 23))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
$data = file_get_contents ("C:\Users\(myUsername here)\Desktop\sockets\Test.txt");
$json = json_decode($data, true);
echo $data . " this is data from file\n";
echo $json . " this is decoded version\n";
echo json_encode($data) . " this is encoded version\n";
$jsonSer = serialize($json);
//socket_write($sock, count($json). "\n\r");
socket_write($sock, $jsonSer);
echo $jsonSer . " this is serialized version\n";
echo unserialize($jsonSer) . " this is unserialized message\n";
//Send the message to the server
//$sock , $message , strlen($message) , 0
//JSON.stringify(data)
if( ! socket_send($sock, $jsonSer, 1024, 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n\r");
}
echo "Message send successfully \n";
?>
And Server.php
<?php
// we create the socket (domain, type, protocol)
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
// AF_UNIX
// if false we pass error code to strerror to get a textual explanation of the error
// and exit execution of the code
if (!$socket) {
echo "Couldn't create socket";
exit(socket_strerror(socket_last_error()));
}
echo "Socket created.\n";
//$address = '127.0.0.1';
//$port = '23';
// we bind the name given in address to the socket
$socket_bound = socket_bind ($socket , '127.0.0.1', 23);
if (!$socket_bound) {
echo "Couldn't bind socket";
exit(socket_strerror(socket_last_error()));
}
echo "Socket bound.\n";
// we tell the socket to listen for incoming connections on socket and keep them in
// backlog (e.g. 25)
$backlog = 25;
$socket_is_listening = socket_listen($socket, $backlog);
if (!$socket_is_listening) {
echo "Socket is not listening";
exit(socket_strerror(socket_last_error()));
}
echo "Socket is listening...\n";
// we set socket to be non-blocking in order to fork connections
socket_set_nonblock($socket);
echo "Waiting for connections...\n";
$server_is_listening = true;
while($server_is_listening) {
// Accept incoming connection
$connection = socket_accept($socket);
if (!$connection){
// we check every 100ms for new connections
usleep(100);
}elseif($connection>0){
// fork connections
// update connections progress and tell the user
// parse json to php object or array (2nd para = 1)
//$database_data_php = json_decode($database_data_json,0);
// accept incoming connection
/* //display information about the client who is connected
if(socket_getpeername($client , $address , $port))
{
echo "Client $address : $port is now connected to us.";
}*/
$response = "Amazing, server responded";
echo "Yay !!! We have a connection\n";
if(socket_getpeername($connection , $address , $port))
{
echo "Client $address : $port is now connected to us. \n";
echo "Connection is: $connection\n";
}
//Now receive reply from server
/*socket_recv ( $connection , $data , 2045 , MSG_WAITALL )*/
//socket_read($connection, 512, PHP_NORMAL_READ);
$input = socket_read($socket, $spawn, 1024);
echo $input . " INPUT";
$buffer = socket_recv($socket, $dataIn, 1024, 0);
echo $buffer . " buffer";
if(!socket_recv($socket, $dataIn, 1024, MSG_WAITALL)){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
$response = unserialize($dataIn);
echo $dataIn;
//echo $buff;
socket_write($connection, $response);
//socket_close($connection);
}else{
echo "Error: ".socket_sterror($connection);
die;
}
}
I use windows 7 atm but the app will be run on unix system in command line. I open 2 cmd windows and start Server.php in first. I start Client.php in the second cmd window. I get the following errors (Server.php).
Socket created.
Socket bound.
Socket is listening...
Waiting for connections...
Yay !!! We have a connection
Client 127.0.0.1 : 50162 is now connected to us.
Connection is: Resource id #5
C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 70
PHP Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 72
Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 72
PHP Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 75
Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 75
Could not receive data: [0] The operation completed successfully.
When I sent a string there was no problem. How do I have proceed with json data please ?
Was given the solution. I need to send json as string and it worked.
Client.php below
$jsonString = "";
$handle = fopen("C:\Users\(myUsername)\Desktop\sockets\Test.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer."\n";
//echo gettype($buffer)." buffer inside";
$jsonString.=$buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
}
socket_write($sock, $jsonString);
fclose($handle);
Server.php below
$jsonString = "";
if(!socket_last_error($socket)){
while($buffer=socket_read($connection,2048)){
//echo $buffer;
$jsonString.=$buffer;
}
}
echo $jsonString;
I hope it can help someone and save some headache.
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.
here is a method in an android application, listen to message send by a php file in a web server
public void run() {
try {
Log.i("------Connect--------", "------------1-------------");
//System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
Log.i("------xxxxxxxxx--------", "------------2-------------");
while (true) {
x++;
Log.i("------xxxxxxxxxx--------","-----------"+x+"-----------");
Log.i("------xxxxxxxxxx--------", "-----------pret de listener------------");
Socket client = serverSocket.accept();
Log.i("------xxxxxxxxxx--------", "-----------en cours de listening-------------");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
Log.i("------xxxxxxxxxx--------", str + "-------------");
//System.out.println("S: Received: '" +);
} catch(Exception e) {
Log.i("------xxxxxxxxxx--------", "S: Error");
} finally {
client.close();
Log.i("------xxxxxxxxxx--------","S: Done.");
}
}
} catch (Exception e) {
Log.i("------xxxxxxxxxx--------","S: Error");
}
the next php code to send a string to an ip from emulator android
<?php
error_reporting(E_ALL);
/* define socket server ip and port here.. */
$socket_ip = "10.0.0.2";
$socket_port = 6060;
set_time_limit(0);
/* create a tcp/ip socket.. */
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
$error = socket_strerror(socket_last_error());
echo "socket_create() failed: [$result] $error\n";
} else {
echo "socket_create() ok.\n";
}
/* connect to socket server ip and port */
$result = socket_connect($socket, $socket_ip, $socket_port);
if ($result === false) {
$error = socket_strerror(socket_last_error($socket));
echo "socket_connect() failed: [$result] $error\n";
} else {
echo "socket_connect() ok.\n";
}
$in = "\r\n\r\n";
$len = strlen($in);
echo "sending input data request.\n";
socket_write($socket, $in, $len);
echo "socket_write() ok.\n";
echo "reading return data.\n";
while ($out = socket_read($socket, 6060)) {
echo "socket_read() : $out";
}
echo "closing the socket.";
socket_close($socket);
echo "socket_close() ok.\n\n";
?>
the problem is when execute command '$ result = socket_connect ($ socket, $ socket_ip, $ socket_port);'finds no answer
If you want to pull data from the server, use Josephs tutorial. If you want to push data from the server to the phone, use Google Cloud Messaging. This way the server can let the phone know that there is new data available. You still need to pull it then. You should not push data through a socket to the phone.