How to identify client PHP Socket?

php, sockets

Solution

If you think about what is delivered in a TCP or UDP packet header, there isn't much identity information included, just the IP address. If you want to know the identity of clients you need to have them send some sort of unique identifier (e.g. username & password as @madara commented). If they're from the same IP that means that they're using the same router in which case its purpose is to mask what devices are behind the router.

To detect who disconnected, you first need to determine who connected. Each connection gets its own socket, even if they're coming from the same IP address. In psuedo php:

// Store all active sockets in an array
$online_users = array();

// Open up a listening socket
$listener = socket_create(...);
socket_listen($listener);
$client_sock = socket_accept($listener);

// Have the client send authentication stuff after connecting and
// we'll receive it on the server side
$username = socket_read($client_sock, $len);
// Map the username to the client socket
$online_users[$username] = $client_sock;

// Continue to read or write data to/from the sockets. When a read or
// write fails, you just iterate through the array to find out who
// it was. If the socket $failed_sock failed, do as follows
foreach ($online_users as $name => $socket)
{
    if ($socket == $failed_sock)
    {
        // $name is the username of the client that disconnected
        echo $name . ' disconnected';
        // You can then broadcast to your other clients that $name
        // disconnected. You can also do your SQL query to update the
        // db here.
        // Finally remove the entry for the disconnected client
        unset($online_users[$name]);
    }
}

Problem

So I've got myself a regular PHP socket (More or less the same code from the example from the php manual). I have found a way to detect when a client disconnects (gracefully or not), but how can I identify who it was? IP address use is out because there might be more than one user with the same IP. Thanks in advance.

Original source