Asaf Nevo
Asaf Nevo

Reputation: 11688

php socket connections

i'm trying to make a php tcp/ip server with the following code:

<?php 
// set some variables 
$host = "localhost"; 
$port = 3804; 

// 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"); 

// accept incoming connections 
// spawn another socket to handle communication 
$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); 

// 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); 
?>

i've randomly choose to work on the 3804 port and when i'm trying to telnet to my host on that port i'm not able to make a connection.. is there any more settings i need to make in the server that the php scripts hosted in, in order to allow my php script to listen to that port ?

Upvotes: 2

Views: 2713

Answers (2)

A B
A B

Reputation: 8876

That code works for me. Are you running this code from apache or another web server? Have you tried running those lines with php -a?

Upvotes: 1

phihag
phihag

Reputation: 288240

Since you pass "localhost" as the second parameter of socket_bind, your socket will only listen to connections from the address localhost resolves to, typically 127.0.0.1. Set $host = '0.0.0.0'; to allow connections from everywhere.

You may also want to configure your firewall(s) to let through connections to port 3804.

Upvotes: 2

Related Questions