PHP7 issue : socket_sendto occurred "Unknown host" - php

Q :
Please let i know why socket_sendto function occurred Unknown host error
env
centos 7.9
php-fpm 7.4 AND php-fpm 8.1
in docker container
/etc/hosts
<docker net ip> <docker container id>
127.0.0.1 nd.domain.com
execution
php -q SERVER.php
source
#!/usr/local/bin/php -q
<?php
// error_reporting(E_ALL);
// set_time_limit(0);
// ob_implicit_flush();
$address = '0.0.0.0';
$port = 80;
echo "server now start\r\n";
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or dir("create failed this socket");
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}
socket_bind($socket, $address, $port) or dir("Failed to bind to (".$address.":".$port.")");
echo "server binded\r\n";
$messageBuffer = "";
$clients = [];
while (true){
if (#socket_recvfrom($socket, $messageBuffer, 2048, MSG_WAITALL, $ip, $port)) {
$address = "$ip:$port";
echo "Receive data : " . $messageBuffer . " FROM " . $address. "\r\n";
if (!isset($clients[$address]))
$clients[$address] = array();
$data = "hello-world";
$client_ip = gethostbyname($address);
echo "callback - send to " . $client_ip . "\r\n";
if (#socket_sendto($socket, $data, strlen($data), 0, $client_ip, $port)) {
echo "sendto ok";
} else {
echo socket_strerror(socket_last_error($socket))."\r\n";
};
} else {
echo socket_strerror(socket_last_error($socket))."\r\n";
};
// $clients[$address]->handlePacket($buffer);
}
socket_close($socket);
//socket_close
// namespace cgiServer;
// include_once './server_fn.php';
// include_once './socketManager.php';
// include_once './socketManagerSessionCtl.php';
// // 무한정 실행하기 위해 시간한계를 0으로 설정한다.
// set_time_limit(0);
// // 대기할 IP 주소와 포트번호를 설정한다
// $unit = new \cgiServer\server\manageUnit('192.168.35.29', 9000);
// //서버 실행
// $unit->serverOpen();
// exit;
?>
server log
with php-fpm 8.1 (display error on)
server now start
server binded
Receive data : hello world FROM 123.123.123.12:12345
callback - send to 123.123.123.12:12345
Warning: socket_sendto(): Host lookup failed [-10000]: Unknown error -10000 in [err-path] on line 47
Unknown error -10000
with php-fpm 7.4 (display error off)
Receive data : 0101010101! FROM 123.123.123.12:12345
callback - send to 123.123.123.12:12345
Unknown host

$client_ip and $address returns 123.123.123.123:12345
$ip returns 123.123.123.123
so i replace like that
#socket_sendto($socket, $data, strlen($data), 0, $client_ip, $port)
to
#socket_sendto($socket, $data, strlen($data), 0, $ip, $port)

Related

can not read serial port using php or nodejs

I have tried to read serial port data sending with arduino by php or nodejs and I couldn't. I think my codes are correct. I think the problem is permission access reading serial port limited by windows or browser but i'm not sure. although the software of arduino can read data.
when I run my codes, arduio sends data over and over but nothing to show data.
can you help me?!
Here my php codes:
<?php
//-- settings --//
//brainboxes serial ports
$portName = "COM5";
$baudRate = 9600;
$bits = 8;
$spotBit = 1;
header( 'Content-type: text/plain; charset=utf-8' );
?>
Serial Port Test
================
<?php
function echoFlush($string)
{
echo $string . "\n";
flush();
ob_flush();
}
if(!extension_loaded('dio'))
{
echoFlush( "PHP Direct IO does not appear to be installed for more info see: http://www.php.net/manual/en/book.dio.php" );
exit;
}
try
{
//the serial port resource
$bbSerialPort;
echoFlush( "Connecting to serial port: {$portName}" );
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
$bbSerialPort = dio_open($portName, O_RDWR );
//we're on windows configure com port from command line
exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
}
else //'nix
{
$bbSerialPort = dio_open($portName, O_RDWR | O_NOCTTY | O_NONBLOCK );
dio_fcntl($bbSerialPort, F_SETFL, O_SYNC);
//we're on 'nix configure com from php direct io function
dio_tcsetattr($bbSerialPort, array(
'baud' => $baudRate,
'bits' => $bits,
'stop' => $spotBit,
'parity' => 0
));
}
if(!$bbSerialPort)
{
echoFlush( "Could not open Serial port {$portName} ");
exit;
}
// send data
$dataToSend = "HELLO WORLD!";
echoFlush( "Writing to serial port data: \"{$dataToSend}\"" );
$bytesSent = dio_write($bbSerialPort, $dataToSend );
echoFlush( "Sent: {$bytesSent} bytes" );
//date_default_timezone_set ("Europe/London");
$runForSeconds = new DateInterval("PT10S"); //10 seconds
$endTime = (new DateTime())->add($runForSeconds);
echoFlush( "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );
while (new DateTime() < $endTime) {
$data = dio_read($bbSerialPort, 256); //this is a blocking call
if ($data) {
echoFlush( "Data Recieved: ". $data );
}
}
echoFlush( "Closing Port" );
dio_close($bbSerialPort);
}
catch (Exception $e)
{
echoFlush( $e->getMessage() );
exit(1);
}
?>
Error in php:
"Warning: dio_open(): cannot open file COM5 with flags 2 and permissions 0: Permission denied in C:\xampp\htdocs\serialreading\SerialPortTest.php on line 42
Could not open Serial port COM5"
Here my nodejs codes:
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM5');
const parser = usbport.pipe(new Readline());
parser.on('data', function (data) {
io.emit('data', { data: data });
});
Error in nodejs:
"Could Not get"

connect multiple device android to the same php socket

My problem is when I try to connect the Android application with Java socket identified by an IP and a port 4444 with a PHP service, identified by the same port, and keep this connection open to accept multiple connections via the Android app.
So with a second Android device if we connect to PHP we will have the same communication channel as the one device and we cannot identify which device is connected via PHP.
Is there a possibility to differentiate these two connections via the PHP file or instantiate two different PHP service for the two devices.
The Android code:
public String connect() {
Socket socket = null;
try {
socket = new Socket();
// This limits the time allowed to establish a connection in the case
// that the connection is refused or server doesn't exist.
socket.connect(new InetSocketAddress(dstAddress, dstPort), context.getResources().getInteger(R.integer.time_out));
// This stops the request from dragging on after connection succeeds.
socket.setSoTimeout(context.getResources().getInteger(R.integer.time_out));
// socket = new Socket();
// socket.connect(new InetSocketAddress(dstAddress, dstPort), 2000);
if (!socket.isConnected())
throw new SocketException("Could not connect to Socket");
DataInputStream DIStream = new DataInputStream(socket.getInputStream());
DataOutputStream DOStream = new DataOutputStream(socket.getOutputStream());
DOStream.write(numCmd.getBytes(), 0, numCmd.getBytes().length);
DOStream.flush();
response = DIStream.readLine();
DOStream.close();
DIStream.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} finally {
if (socket != null) {
try {
socket.close();
if(response == null){
response = "{\"Error_no\":5000}";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
}
}
}
// Log.i("resp",response);
return response;
}
The PHP code:
<?php
echo "service php started \n";
$version = '2.2.0';
$address = '10.164.2.1';
$port = 4444;
$timeout= 2;
$cmd = explode("*", str_replace(array("/"), "*",
str_replace(" ","",shell_exec("netstat -tulpn | grep :".$port))));
echo "pid ".$cmd[1];
$cmd[1] = substr_replace($cmd[1], '', 0, 6);
echo "pid ".$cmd[1];
exec("kill -9 $cmd[1]");
sleep(1);
$socketPath = 'unix:///home/root/sockets/local_iapp_socket';
// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
if(socket_bind($server, $address, $port)){
echo "Connected with tcp socket \n";
}else{
echo "connection with tc socket error \n";
}
socket_listen($server);
echo "server is listning \n";
$socket_fd = connect_socket_local();
echo "connected to unix socket \n";
while ($client = socket_accept($server)) {
$num_cmd = socket_read($client, 5000);
echo "Client Message : ".$num_cmd ."\n";
if($socket_fd != false){
$id=24;
$len= strlen($num_cmd);
$fwrite1 = fwrite($socket_fd, pack("L", $len),4);
if($fwrite1 === false){
$content = '{"Error_no":5000}';
echo "fwrite1 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$fwrite2 = fwrite($socket_fd,pack("L", $id),4);
if($fwrite2 === false){
$content = '{"Error_no":5000}';
echo "fwrite2 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$fwrite3 = fwrite($socket_fd,$num_cmd,strlen($num_cmd));
if($fwrite3 === false){
$content = '{"Error_no":5000}';
echo "fwrite3 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$content = fread($socket_fd, 5000) ;
if( $content == null){
echo "impossible d'atteindre la socket locale" . socket_strerror(socket_last_error()) . "\n";
$content = '{"Error_no":5000}';
}
}else{
$content = '{"Error_no":5000}';
echo "problème de connexion" . socket_strerror(socket_last_error()) . "\n";
}
$json_resp = $content;
echo "json_resp" . $json_resp."\n\r";
socket_write($client, $json_resp,strlen($json_resp));
socket_close($client);
}
socket_close($server);
function connect_socket_local()
{
global $socketPath , $timeout;
if (($socket_fd= stream_socket_client($socketPath , $errorno, $errorstr, $timeout)) === false) {
echo "stream_socket_client a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
}
return $socket_fd;
}
?>
You can run a separate server process for each client. Each server process needs to have an unique IP address or TCP port. Each client needs to be configured to connect to the correct server address and port. This is difficult to manage and doesn't scale.
At the server side, you can get the peer address, that is the IP address and port of the client. In PHP, you can use socket_getpeername() for this. However, depending on the network setup, this might not be the IP address of the client itself. It can be the IP address of an intermediate gateway or other network device. Also, the client IP address might be dynamic.
The best solution is to send some identification from the client to the server when the clients connects to the server. This can be a name or some other unique identification. You have to change the protocol between the client and server to support this. The client needs to know when and how to send the identification. The server needs to know when and how to receive the identification.

How can i run socket server in PHP?

How can i run socket server for each www client?
I have simple socket_server:
<?php
// set ip and port
include('socket.php');
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "-1";
exit;
}
// bind socket to port
$result = socket_bind($socket, $host, $port) or die(socket_strerror(socket_last_error($socket)));
// start listening for connections
$result = socket_listen($socket, 3);
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Server: Ready.";
while(1) {
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input."<br />";
// reverse client input and send back
//$output = strrev($input) ."<br />";
$output = "output message";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
}
// close sockets
socket_close($spawn);
socket_close($socket);
?>
Now when i try run server in this way:
<?php
//include the server.php script to start the server
include_once('server.php');
include('socket.php');
$message = "Hello Server";
echo "Message To server :".$message;
// 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");
// 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");
echo "Reply From Server :".$result;
// close socket
socket_close($socket);
?>
I get the message:
Only one usage of each socket address (protocol/network address/port) is normally permitted.
I do not have any other communications on this port. I checked the netstat.

Send TCP packet in PHP

I tried to send a TCP packed data to a some ip with php , i used the code below to send it :
$socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//$bind=socket_bind($socket,'tcp://94.232.171.102');
socket_connect($socket, 'xx.xx.xx.xx', 9001);
$buff='P\00\00\00\e5G\1f\b9\c6\acB\84\15\e7\b3*\17\ab\00G2\n\9c\ba{\a9}\dab"\c31\ed\f7\94\fc\aeX\ab\13\r/\02\ce\83f\bc?\96q\10M\b0\f4\a0\b1\95X\d0\85\10\df$|\de$\b4\f6m\a9\ff%Z\b4\d8\aa\da\bb';
$length = strlen($buff);
$sent = socket_write($socket, $buff, $length);
But, however, it doesnt work and doesnt sent , when i use some windows application like Packet Sender for that setting it's send packet correctly , why i cant send it from php on localhost
With at least some error handling you have a better chance of finding the error.
ini_set('display_errors', true); error_reporting(E_ALL); // <- for debugging purposes only
$socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ( !$socket ) {
$errno = socket_last_error();
$error = sprintf('%s (%d)', socket_strerror($errno), $errno);
trigger_error($error, E_USER_ERROR);
}
if ( !socket_connect($socket, 'xx.xx.xx.xx', 9001) ) {
$errno = socket_last_error($socket);
$error = sprintf('%s (%d)', socket_strerror($errno), $errno);
trigger_error($error, E_USER_ERROR);
}
$buff='P\00\00\00\e5G\1f\b9\c6\acB\84\15\e7\b3*\17\ab\00G2\n\9c\ba{\a9}\dab"\c31\ed\f7\94\fc\aeX\ab\13\r/\02\ce\83f\bc?\96q\10M\b0\f4\a0\b1\95X\d0\85\10\df$|\de$\b4\f6m\a9\ff%Z\b4\d8\aa\da\bb';
$length = strlen($buff);
$sent = socket_write($socket, $buff, $length);
if ( FALSE===$sent ) {
$errno = socket_last_error($socket);
$error = sprintf('%s (%d)', socket_strerror($errno), $errno);
trigger_error($error, E_USER_ERROR);
}
else if ( $length!==$sent ) {
$msg = sprintf('only %d of %d bytes sent', $length, $sent);
trigger_error($msg, E_USER_NOTICE);
}

Writing a UDP packet forger in PHP

I am working on an UDP spoofer written in PHP and I wanted to know how can I forge those packets. Any help is appreciated. Thank you!
The following function will create a socket in PHP with a port number. Depending on what you are spoofing, you will need to modify the 'message'. In the example below is in clear text but often applications transmit this in the form of binary information which will need to be reserve engineered to spoof it.
function sendUDP($host, $msg, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
socket_connect($socket, $host, 8000); //Set up to send to port 8000, change to any port
socket_send($socket, $msg, strLen($msg), 0);
$buf = "";
$from = "";
$port = 0;
#socket_recvfrom($socket , $buf , 24 , 0 , $from , $port );
socket_close($socket);
return $buf;
}
just read those code:
server.php
<?php
//error_reporting( E_ALL );
set_time_limit( 0 );
ob_implicit_flush();
$socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
if ( $socket === false ) {
echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n";
}
$ok = socket_bind( $socket, '202.85.218.133', 11109 );
if ( $ok === false ) {
echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) );
}
while ( true ) {
$from = "";
$port = 0;
socket_recvfrom( $socket, $buf,1024, 0, $from, $port );
echo $buf;
usleep( 1000 );
}
?>
client.php
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$msg = 'hello';
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, '202.85.218.133', 11109);
socket_close($sock);
?>

Categories