14.7 Handling Multiple IP Addresses


You want to write a server that is aware that the machine on which it runs on has multiple IP addresses, and it should do different things for different addresses.

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 .



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net