Hello i'm trying to learn and build a socket script in PHP this is my code:
Client:
include_once('server.php');
$host = "localhost";
$port = 1025;
$message = "Hello Server";
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
// connect to server
socket_bind($socket, $host);
if (socket_connect($socket, $host, $port) === false) {
echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
else { echo "Connected"; }
Server:
// Variables
$host = "localhost";
$port = 1025;
// No timeout
set_time_limit(0);
// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Can't create socket..");
if ($socket === false) {
echo "Unable to create socket. Error: {$errno} : {$errstr}\n";
die();
}
// Bind Socket
if (socket_bind($socket, $host) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
else { echo "Connected to {$host}:{$port}"; }
// Socket listen
if (socket_listen($socket, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
if (socket_accept($socket) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
// Socket close
socket_close($socket);
But i'm missing something that i cant figure out and i dont know what, When im trying to connect from the client it just loads nothing happens, Can anyone here point me in the right direction and tell me what im doing wrong?
On your client, you do not want socket_bind(). That is for opening up a connection for other systems to connect to; in short, to become a server.
Our client script:
<?php // client.php
$host = "127.0.0.1"; // connect _does_ do DNS lookups, unlike bind, which is mentioned below, but for simplicity of the example I'm explicitly naming the IP address.
$port = 1025;
$message = "Hello Server";
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
// Using die() here because we really don't want to continue on while in an error condition.
die('socket_create() failed: reason: ' . socket_strerror(socket_last_error($socket));
}
// connect to server
if (socket_connect($socket, $host, $port) === false) {
die('socket_connect() failed: reason: ' . socket_strerror(socket_last_error($socket));
}
socket_write($socket, $message);
socket_close($socket);
In your server, you should listen on 0.0.0.0 (or a specific IP address), and not specify a domain name. 0.0.0.0 means to listen to all IP addresses, and any specific IP address means to only listen on the one interface that is configured for that address.
For example, if your server has 2 NICs, one assigned to a public address, say 1.2.3.4, and another assigned to a local address, 192.168.0.2. You also always have your loopback, 127.0.0.1 for free just by having TCP/IP.
If you want to restrict access to your server script to only other hosts on your network, you would set your listen address to 192.169.0.2. Even though your server is accessible through the public IP of 1.2.3.4, this script will simply not listen to any of that traffic.
If you want to restrict access to your server script to only other processes running on that machine, you need to use 127.0.0.1. Using "localhost" will not keep anyone out, because bind does not perform any DNS lookups (and PHP's socket_bind() is only a thin wrapper around the BSD Sockets based system call to bind). It doesn't even look at the hosts file. Thus, any non-IP string will be cast to an integer, usually resulting in it becoming 0, and that 0 will be converted to 0.0.0.0, which will allow access from all interfaces, despite you thinking that you're only listening to localhost traffic.
When you accept a connection, it creates a new socket resource, which I've named $clientSocket in the example below. Don't get confused between the sockets created when a new host connects and your listening socket; they're very similar, but with a very important distinction: When your listening socket has a new message, it is always saying that there is a new host connecting, so you should accept. If it is a client socket, then you'll be using read or recv. (I prefer recv because of the finer control, but I use read in the example below to more clearly show the process rather than adding confusion by having references... which is also why I'm not going to show select.)
Our server script:
<?php //server.php
$listen_address = "0.0.0.0";
$port = 1025;
$maxBuffer = 1024; // bytes, not characters.
// No timeout
//set_time_limit(0); // Shouldn't be necessary in CLI.
// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
die('Unable to create socket: ' . $socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
// Bind Socket
if (socket_bind($socket, $listen_address, $port) === false) {
die('socket_bind() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
else {
echo "Connected to {$listen_address}:{$port}\n";
}
// Accept our client connection
// Typically, this would be where we'd put a loop with socket_select,
// but for our example, since we'll be exiting as soon as we have our
// first packet, we'll listen, accept, read, then close.
if (socket_listen($socket) === false) {
die('socket_listen() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
$clientSocket = socket_accept($socket);
if ($clientSocket === false) {
die('socket_accept() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
}
// Because the contents of a packet could be longer than our
// buffer size, it's advisable to peek at the socket to see
// if it would block before saying that our message is complete.
// In our example, we're receiving 12 bytes out of our maximum 1024,
// so I leave handling large packets as an exercise for the developer.
$message = socket_read($clientSocket, $maxBuffer);
var_dump($message);
// Socket close
socket_close($clientSocket);
socket_close($socket);
And finally, here's how to run the mess above.
Note that I'm going to have both the server and client run in the same TTY, I'll have the server run as a background process (use the & modifier), but I will not be redirecting their output, so both scripts will be spitting their output into the same terminal.
myhost.mydomain$ php ./server.php &
[8] 76399
Connected to 0.0.0.0:1025
myhost.mydomain$ php ./client.php
string(12) "Hello Server"
[8]+ Done php ./server.php
Your implementation of the server is wrong. Your server should have a loop which is always active listening to connections.
Server
# Create Socket
$socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
# Bind a host and a port to the socket
socket_bind($socket, $host, $port);
# Listen for connection in the socket you just created
socket_listen($socket);
# This is the heart of the server, without it, it can not serve.
while(true)
{
# Accept Client connection if client socket connects
$client = socket_accept($socket);
# Logic #todo Reponse to client
print "Connected." // For testing purposes, see if client actually connected
# Close client connection
socket_close($client);
}
To connect from your client to the server use socket_connect, documentation here.
Related
I have lots of questions about PHP sockets.
I successfully done the socket_write() part, but not socket_listen()
As my socket_bind() didn't open any port (I am not sure if bind should open port or just bind ip's, but when I write my phone IP it told can't assign requested IP, and when I tried socket_connect it returned error[111], and when I checked with netstat and telnet the port wasn't open) I decided to open port with nc
nc -kl 47832
Then I wrote this in my test.php file
so the code checks if I am with my PC(localhost) it should connect to 127.0.0.1
and if I am with phone (not localhost) it connects to 192.168.43.124 (My PCs IP)
$forloop;
if ($_SERVER["HTTP_HOST"]=="localhost") {
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Err: " . socket_last_error());
socket_connect($socket, "127.0.0.1", 47832) or die("Err: " . socket_last_error());
$result = socket_listen($socket) or die("can't set up listener");
$spawn = socket_accept($socket) or die("err: can't accept");
$input = socket_read($spawn, 1024) or die("Could not read input\n");
$resinput = trim($input);
//echo socket_get_option();
socket_close($spawn);
socket_close($socket);
}
else {
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Err: " . socket_last_error());
socket_connect($socket, $_SERVER['HTTP_HOST'], 47832);
socket_write($socket, "needreload", 10) or die("Could not write output\n");
sleep(1);
socket_close($socket);
}
function whilefunc() {
$GLOBALS['forloop'] = 1;
if (!isset($GLOBALS['forloop'])) {
while ($GLOBALS['forloop'] == 1) {
if ($GLOBALS['input']=="needreload") {
//loadchat();
socket_successful();
}
}
}
}
function socket_successful() {
$GLOBALS['forloop']=0;
echo "<h2>msg recieved:" . $GLOBALS['input'] . "</h2>";
$resinput="";
whilefunc();
}
whilefunc();
Now when I open the page with phone in terminal text "needreload" appears, but
when I open it with PC it says can't set up listener (and that's because I didn't used bind, but if I used bind it would have told can't bind address already in use).
I changed my test.php a lot but still don't know what to do..
So my questions are
How to fix this using socket_bind() (as after I can't socket_connect, cause no port is being opened)
how to fix this (nc port opened method).
I know I wrote my question mixed, but that's because I am also confused.
For me adding this ob_implicit_flush(); to my code, made my socket accessible from telnet and nc.
I am running an apache2 server from a windows computer using the Linux subsystem. Now I'm trying to use it as a server and listen to connections. Unfortunately it is failing when trying to bind to the socket. This is the code:
$host = '0.0.0.0';
$port = 1433;
set_time_limit(0);
if(!$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) {
die("Couldn't create socket! reason: " . socket_strerror(socket_last_error()) . "\n");
}
if(!$result = socket_bind($socket, $host, $port)) {
die("Couldn't bind socket! reason: " . socket_strerror(socket_last_error()) . "\n");
}
The error code just states that permission is denied, however I have allowed this specific port through my firewall. I am quite new to the whole php server-side thing, so I would really appreciate any help!
I hope that I do not ask a spam question because I can not find any question about it.
I write a socket port listener to listen an specific IP:PORT using PHP to receives TCP Packets from GPS Tracking Devices.
When I run script with this command:
$php.exe -q My/Script/Files/Path.PHP
everything is okay and my Server port listener works successfully and I receive data from devices but when I want open that with my browser (wamp -> localhost) it's said that
Warning: socket_bind(): unable to bind address [10049]: The requested address is not valid in its context.
How I can Solve This Problem?
Best Regards.
Edit One:
My Server Script Code:
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '*.*.*.*'; //I put Here My System Local IPV4 Address (163.*.*.*)
$port = *****; //I put Here My Server Opened Port Number and I turned off the firewall to test
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, 1) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if ($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
}
$buf = trim($buf);
$clientResponse = explode(',', $buf);
foreach($clientResponse as $key=>$value) {
echo $key . ' : ' . $value . "<br />";
}
socket_close($msgsock);
socket_close($sock);
?>
As I said before:
When I run this script with PHP CLI, everything is okay and my device sends TCP Packet and My server receives TCP Packet and show that information. But when I run it By wamp with it local IP 127.0.0.1, it gave me that error.
till here:
I have a VPS Server
I have a Static IP (Public IP)
I have an Open TCP port with off firewall
I have a local IP
I have a wamp with IP:Port -> 127.0.0.1:80
Edit Two:
My Script Port: 41260
I google some keywords and I find this docs : (Bind) in Apache's official Site. And I decided to share the result to other users.
I am working on PHP socket programming project. In this project we are going to create a service in php socket. This socket will listen on one particular port. And client from outside network will able to communicate on that port.
Till now I am able to create server and client in php for socket programming. Now my pc is connected to LAN so I have to use port forward for connecting my pc with outside client. I forward port 2000 and all communication on that port is transfer to my pc IP address. I have netgear router n150 wireless adsl .I add all configuration on that router. I test port forwarding online at this site http://www.yougetsignal.com/tools/open-ports/ it says port is open.
I test my code on locally (intranet), it is working fine. But when I trying to run server on my pc and client from web server which is my ipage hosting server. It throws me error "Server Could not connect to server".
Server.php
<?php
// set some variables
// My LAN Ip
$host = "192.168.0.5";
$port = 2000;
// don't timeout!
set_time_limit(0);
// 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");
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// 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;
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>
Client.php
<?php
//my public ip
$host = "117.223.90.191";
// port on which I port forword
$port = 2000;
$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);
?>
Any suggestion for problem. I think many will have same problem like me.
Even if i think the problem is in the lan forwarding, try testing it with :
telnet 117.223.90.191 2000
another thing to try is to make the server listen on all interfaces
$host = "0.0.0.0";
and take a look at http://reactphp.org/
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.