bob c
bob c

Reputation:

Miniature PHP webserver not accepting connections on anything other than 127.0.0.1:80

I've created a miniature 'web server' that simply returns one message to any request sent to it on port 80. I can connect to it via http://127.0.0.1/ but when I try to connect to it with my actual IP address, nothing comes through.

Code:

# config
$conn_ip = "127.0.0.1"; // probably localhost
$conn_port = 80; // port to host 'server' on
$conn_max  = 5; // max connections to accept
# end config

$output = 'blah';

# prepare php script
set_time_limit(0);
ob_implicit_flush(true);
# end

# setup the socket
$server = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($server,$conn_ip,$conn_port);
socket_listen($server,$conn_max);
# end

print "listening on port 80...\n\n";

# loop
while (true) {
 if (($new_sock = socket_accept($server)) !== NULL) {
  print("got connection...\n");
  socket_write($new_sock,$output,strlen($output));
  socket_close($new_sock);
     }
}
# end

?>

What am I doing wrong here?

Upvotes: 0

Views: 299

Answers (2)

Tarnay Kálmán
Tarnay Kálmán

Reputation: 7066

Change this line

$conn_ip = "127.0.0.1"; // probably localhost

to

$conn_ip = 0;

  • 127.0.0.1 means that your "webserver" will only listen for connections only on 127.0.0.1 (localhost)
  • 0 means that your "webserver" will listen on each and every IP of your computer

Upvotes: 2

brianegge
brianegge

Reputation: 29872

Change your socket bind to:

socket_bind ($server, 0,$conn_port);

By specifying a $conn_ip, you are only binding to that interface. In this case, you are binding to the loopback. This is the default for testing, as you may not want to allow the world to connect to your service when you first start writing it.

Upvotes: 0

Related Questions