socket_bind problem

I am currently working on a project that requires me to connect to a server and send messages between my site and the server.

For example:

Visitor comes to my site, site sends message to server saying “new visitor”

Server sends back “welcome”

My site displays “welcome” on the page - the message sent back by the server

To do this I have found the following code and expected it to work, unfortunately I am getting an error.


error_reporting(E_ALL | E_NOTICE | E_STRICT);
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);

// set some variables
$host = ""; // server IP goes here
$port = 1234; // port thats listening goes here

// don't timeout!
set_time_limit(0);

// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);

// Bind the socket to an address/port
socket_bind($sock, $host, $port) or die('Could not bind to address '.socket_last_error());

// Start listening for connections
socket_listen($sock);

// Accept incoming connections
$client = socket_accept($sock);

// Send message to user
$message = "This is a test message";
socket_write($client, $message);

// Read user input and loop until
// it says 'quit'
$messageback = socket_read($client, 1024);

echo $messageback;

// Close the client (child) socket
socket_close($client);

// Close the master sockets
socket_close($sock);

This produces the following error:


Warning: socket_bind() [function.socket-bind]: unable to bind address [99]: Cannot assign requested address in /home/sites/domain.com/public_html/index.php on line 35
Could not bind to address 99

I’ve been doing some tests to try and narrow down the problem. The server is running fine and accepting connections, and doesn’t care if more than one connection at a time comes through. I can telnet into the server, both from my PC and also via SSH where the site is hosted.

So this suggests that there’s nothing other than the PHP code that’s causing an issue. There might be something blindingly obvious that I’ve not done but the socket functions in PHP are one of the few things I’ve never used before.

Hopefully someone can help!

Are you trying to bind the socket to a local IP address?

I assume that what you have is two servers -

server A - hosts your website, it will conect to server B as needed
server B - generates text responses for your visitors, it listens for requests from server A and responds asap.

The code snipet you sent was for server B?

Yes that’s correct it’s 2 separate servers as you said, the code snippet is hosted on Server A and trying to send messages to Server B

I have never used sockets in php, but have wused them in C before… what I think you need to have:

Server A:

s = socket()
connect(s, serverB_address);
read/write(s, )

Server B:

s = socket()
bind(s, local_ip_address, most likely the same as serverB_address above)
listen(s)

in a loop:
(optional) select( ); // wait for a rd event on s
s2 = accept(s)
read/write(s2, )

Does that make sense?