PHP Developers Cookbook (2nd Edition)
Technique
Bind your server to INADDR_ANY instead of a specific address, and then get the server's address and port using the getsockname() function: <?php $sock = socket(AF_INET, SOCK_STREAM, 0); if ($sock < 0) die(strerror($sock)); if (($ret = setsockopt($sock, SOL_SOCKET, SO_REUSEADDR, 1)) < 0) die(strerror($ret)); if (($ret = bind($sock, INADDR_ANY, $port)) < 0) die(strerror($ret)); while (($csock = accept_connect($sock)) >= 0) { if (($ret = getsockname($csock, $name, $port)) < 0) return; // Manipulate Hostname, $name and with Port, $port, here. } ?> Comments
To bind your socket to all the available IP addresses on your system, use the bind() function along with the INADDR_ANY option. When you receive a new connection, you can use the getsockname() function to get the current socket's name and information. That way you know what IP address the user connected to and you can treat the connection accordingly . |