socket connection code of php - php

I am writing a simple php socket code.
Here is my code
<?php
$address="127.0.0.1";
$port=9875;
echo "I am here";
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
echo "client is here";
?>
when I run this program my browser only shows waiting for localhost.
Is there any problem in my code?
I am using xammp 1.7.4 .
Another thing I want to know if I want to get a HTTP or FTP request do I have change only the port number?

I verified the code and tested in my system and it works correctly. Showing as "client is here" after running the client.
File Name: server.php
<?php
$address="127.0.0.1";
$port=9875;
echo "I am here";
set_time_limit (0);
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
echo "client is here";
socket_close($socket);
?>
First run the server.php file.
File: client.php
<?php
$host="127.0.0.1" ;
$port=9875;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo "Connected";
}
?>
Now run the client.php
Your output should be like this (as I got in my system)
I am hereclient is here
If not, make sure your firewall is not blocking the request. Temporarily disable antivirus if you have one.

That is the expected behaviour of waiting.
The program you have written is a socket server which is ready to listen to the connection with the specified port, until then it will wait.
You can create a client who connects so that you will see the response "Client is here". The client can be any programming language including PHP.
Below is a sample code in PHP (I didn't verify it).
$fp = stream_socket_client("127.0.0.1:9875", $errno, $errstr);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
// Handle code here for reading/writing
}
You can check this link for sample client code in PHP.
EDIT
$host = "127.0.0.1";
$port = 9875;
$timeout = 30;
$sk = fsockopen($host, $port, $errnum, $errstr, $timeout);
if (!is_resource($sk)) {
exit("connection fail: " . $errnum . " " . $errstr);
} else {
echo "Connected";
}

Related

PHP socket: unable to connect [10048]: Only one usage of each socket address (protocol/network address/port) is normally permitted

I run the server.php then run client.php and this warning show on the client.php screen after several try to send from client to server.
Warning: socket_connect(): unable to connect [10048]: Only one usage of each socket address (protocol/network address/port) is normally permitted. in C:\xampp\htdocs\client.php on line 32 Socket connection failed!
After that xampp stopped working.
Here is server.php
<!DOCTYPE html>
<html>
<?php
error_reporting(0);
set_time_limit(0);
ob_implicit_flush();
$host = "127.0.0.1";
$port = 65535;
echo "Waiting for connections... \n";
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
$result = socket_listen($socket) or die("Could not set up socket listener\n");
while(1){
$spawn[++$i] = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "\n";
$input = socket_read($spawn[$i],1024);
$client = $input;
echo $client ."\n";
socket_close($spawn[$i]);
echo "\n";
}
socket_close($socket);
?>
</html>
Here is my client.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="client.php">
<p><h4><label>Type Your Message Here:<input name = "message" size = "25" maxlength = "30" required></label></h4></p>
<input type="submit" name="sendmsg" class="btn btn-primary" value="send message"/>
</form>
<?php
$user="abc";
if(empty($_POST)){
}
elseif(isset($_POST['sendmsg'])) {
$message =$_POST["message"];
while(1){
if($message=='q') { exit; }
$socket= socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket===false)
{
echo "Socket creation failed!";
}
$result = socket_connect($socket,"127.0.0.1",65535);
if($result===false)
{
echo "Socket connection failed!";
}
else {
if($message !='0'){
socket_write($socket,"$user says --> $message",1024);
$message='0';
}
}
socket_close($socket);
}
}
?>
</body>
</html>
You are continually creating, connecting and closing sockets, inside the while(1) with minimal delay between them. It's likely that you are consuming all the ports available as as the originating endpoint, as it would take time to close the socket.
Did you mean to only create a connection whenever the page is POSTed to with a new message?

Socket_read() says "not a valid resource"

I am learning socket programming and experimenting using php.
I wanted to connect to a socket-server using a client and read the response of the server from the client.
Codes for :
Server.php:
$address="127.0.0.1";
$port=3343;
echo "I am here";
set_time_limit (0);
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
socket_write($client, "Welcome!!", 1024);
socket_close($socket);
Client.php
$host="127.0.0.1" ;
$port=3343;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo socket_read($sk, 256);
//echo "Connected";
}
On connecting,
Server output :
I am here
Client Output :
Warning: socket_read(): supplied resource is not a valid Socket resource in C:\xampp\htdocs\users\srv\test\client.php on line 16
Found the problem here.
socket_read() doesn't work with sockets which have not been created with socket_create().
Working code :
$host="127.0.0.1" ;
$port=3343;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
while (!feof($sk)) echo fgets($sk, 256); //This does the trick
//echo "Connected";
}
You are mixing the resource types.
fsockopen returns a file pointer. You need to use fread, fwrite etc. on it, and not socket_read.
socket_read accepts socket resources create with socket_create or socket_accept
Example for fsockopen from the PHP manual page:
<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($fp, "\n");
echo fread($fp, 26);
fclose($fp);
}
?>
fsockopen reference
socket_read reference

PHP how to connect with sockets and read the response?

The title explains it all...
How can i connect to an IP using tcp protocol and read/get the response?
I have searched a lot but i didnt find any solution.
$socket = stream_socket_server("tcp://127.0.0.1:22", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
echo fread($conn, 26);
fclose($conn);
}
fclose($socket);
}
is this code ok?
Does the job?
Because it seems it doesn't do the job...
Thanks in advance
As suggested by others; avoid using port 22. I recommend using an obscure (unused) socket port number > 1024 such as 4444. Anything below 1024 normally requires root access.
If you need to test connectivity for 22 have your server script run additional functions.
As for sending a response back to the connected client use stream_socket_recvfrom($socket, $length, 0, $peer) instead of fread()
Then on the client side add a response listener:
client.php
$socket = stream_socket_client('tcp://127.0.0.1:4444');
if ($socket) {
$sent = stream_socket_sendto($socket, 'message');
if ($sent > 0) {
$server_response = fread($socket, 4096);
echo $server_response;
}
} else {
echo 'Unable to connect to server';
}
stream_socket_shutdown($socket, STREAM_SHUT_RDWR);
server.php
$conn = stream_socket_server('tcp://127.0.0.1:4444');
while ($socket = stream_socket_accept($conn)) {
$pkt = stream_socket_recvfrom($socket, 1500, 0, $peer);
if (false === empty($pkt)) {
stream_socket_sendto($socket, 'Received pkt ' . $pkt, 0, $peer);
}
fclose($socket);
usleep(10000); //100ms delay
}
stream_socket_shutdown($conn, \STREAM_SHUT_RDWR);
Run server.php which will listen in an endless loop listening for a non-empty packet
once server.php receives a packet it will respond back to the connected client with the received packet.
Then execute client.php which will send 'message' to server.php
Once sent it will then retrieve and echo the response from server.php which should read 'Received pkt message'
From http://php.net/stream_socket_accept
Accept a connection on a socket previously created by stream_socket_server().
That means it waits that one client wants to connect. (You just bind yourself to the port, but don't connect anything)
And fread is also the wrong function to use with socket_* functions. Correct function would be stream_socket_recvfrom().
But this really isn't what you seem to want. You appearently want to open a connection to some place. So fsockopen() is the right function:
$conn = fsockopen("127.0.0.1", 22, $errno, $errstr);
if (!$conn) {
echo "$errstr ($errno)<br />\n";
} else {
echo fread($conn, 26);
fclose($socket);
}

Query if Shoutcast Server is Offline or Online with PHP

I'm trying to use a script to query if a Shoutcast Server is online or offline. The code below is what I'm using at the moment.
$vt_ip = "ip";
$vt_port = "port";
$output = #fsockopen($vt_ip, $vt_port, $errno, $errstr, 2);
if (!$output) {
echo "<FONT CLASS=f1 COLOR=#DD0000><B>OFFLINE</B></FONT>";
} else {
echo "<FONT CLASS=f1 COLOR=#00DD00><B>ONLINE</B></FONT>";
}
#fclose($output);
But it doesn't update, it is stuck on Offline status.
Any help would be greatly appreciated.
$vt_ip = "ip";
$vt_port = "port";
$conn = fsockopen($vt_ip, $vt_port, $errno, $errstr, 2);
if(!$conn){
echo $errno;
}else{
fwrite($conn, "\n");
$output = fread($conn, 1024);
fclose($conn);
if ($output == "") {
echo "<FONT CLASS=f1 COLOR=#DD0000><B>OFFLINE</B></FONT>";
} else {
echo "<FONT CLASS=f1 COLOR=#00DD00><B>ONLINE</B></FONT>";
}
}
It isn't enough to simply make a TCP connection to a SHOUTcast server to determine if the stream is working. In fact, a SHOUTcast server that is running will always accept yourTCP connection, even if there is no stream for playback.
You must connect, request the stream, and then check the return status code. Once connected, send this data:
GET /; HTTP/1.0
Follow that by a \r\n\r\n. Now, read data back from the stream until you get the \r\n\r\n. Then, you can disconnect. Check the status code from the first response line and see if it's 200. If it is, you've got an active stream.

unable to bind address [0]: php error

unable to bind address [0]: Only one usage of each socket address (protocol/network address/port) is normally permitted....
error is given by my php server page. I tried different port numbers as looking from cmd as writing netstat -an. Also I searched on google but no solution. I am using wamp server and working local .
Thanks .
<?php
// don't timeout
//echo phpinfo();
set_time_limit (0);
// set some variables
$host = "127.0.0.1";
$port = 1234;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
echo "Waiting for connections...\n";
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Received connection request\n";
// write a welcome message to the client
$welcome = "Roll up, roll up, to the greatest show on earth!\n? ";
socket_write($spawn, $welcome, strlen ($welcome)) or die("Could not send connect string\n");
// keep looping and looking for client input
do
{
// read client input
$input = socket_read($spawn, 1024, 1) or die("Could not read input\n");
if (trim($input) != "")
{
echo "Received input: $input\n";
// if client requests session end
if (trim($input) == "END")
{
// close the child socket
// break out of loop
socket_close($spawn);
break;
}
// otherwise...
else
{
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output . "? ", strlen (($output)+2)) or die("Could not write output\n");
echo "Sent output: " . trim($output) . "\n";
}
}
} while (true);
// close primary socket
socket_close($socket);
echo "Socket terminated\n";
?>
Erm...this is running on a web page? If so, each hit to the page will cause the script to try to bind to port 1234, which ain't gonna happen for any but one at a time. All the others will die.
If it's not, then there are two reasons i can think of right off why binding would fail: either another program is already using the port, or the firewall is blocking it. The latter shouldn't be the case for 127.0.0.1, but i've seen stranger things happen.
The code as posted should work, at least it does here. Are you sure there is no firewalling thing preventing you from opening the socket?
It shouldn't matter much, but when opening the socket, specify the right protocol:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
If that doesn't help, try a loop to find a listening port that may work; maybe the port is still blocked by your previous attempts.
for ( $port = 1234; $port < 65536; $port++ )
{
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
if ( $result )
{
print "bind succeeded, port=$port\n";
break;
} else {
print "Binding to port $port failed: ";
print socket_strerror(socket_last_error($socket))."\n";
}
}
if ( $port == 65536 ) die("Unable to bind socket to address\n");
If this solves your problem, you may want to do
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
before binding, to tell the system that it should allow reuse of the port.

Categories