I have a small web server script. If I set it to ‘localhost’ – then I can’t telnet to that port from outside. If I set it to the FQDN – then I can’t telnet like this: ‘telnet localhost 7777’. What is the proper way to name the host in this case?
$host = 'localhost';
$port = 7777;
set_time_limit(0);
$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, 3) or die("Could not set up socket listener\n");
while(1)
{
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
$input = socket_read($spawn, 1024) or die("Could not read input\n");
while(trim($input)!="")
{
$msg=$msg.$input;
$input = socket_read($spawn, 1024) or die("Could not read input\n");
}
$webserver = new Server($msg);
$output = $webserver->response();
unset($msg);
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
socket_close($spawn);
}
Yes. You have two options. The easiest way is to bind the socket to
0.0.0.0, which will bind the socket to all the interfaces on the machine. (Make sure though, that you actually want all interfaces.)Otherwise, you can always create >1 socket, and bind them individually to the interfaces that make sense.
You’re writing the whole webserver in PHP?
Also, if PHP’s socket reading functions work like most operating systems, then your inner loop probably isn’t correct: while an HTTP request does end with a blank like, that doesn’t mean that the OS’s
readfunction is going to segment data line by line.Edit:
socket_readapparently will segment results by lines (this is unusual), but you need to specify it as the third parameter. According to the documentation, the default will not segment by line, but that this wasn’t always the case — i.e., the default changed. You should probably specify it to make sure your code doesn’t break when you upgrade. (And maybe upgrade, while you’re at it…)