[ale] Python (or other) socket identification

Alex Carver agcarver+ale at acarver.net
Fri Feb 3 15:20:57 EST 2017


On 2017-02-03 05:42, Ed Cashin wrote:
> You can use the IP as the key in a dict, and any object you want can be the 
> value.  I'm not sure what the identifiers are doing in your example, though.

Right, I have that already.  The problem was the reverse condition,
using an object as the key and the IP as the value.  The reasoning:

Remote device R1 establishes a connection to the daemon.  The daemon
accepts and stores the new client socket object S1.  Another remote
device R2 does the same and socket object S2 is stored for it.  Repeat
as needed for all devices.

After accepting, obtain the IP of Rx and store Sx_object in a dict keyed
on IP:

sockets_by_ip[Sx_object.getpeer()] = Sx_object

If I want to send a message to R1, I know ahead of time what its IP is
but I don't know which socket is currently open to that device.  So I
use my dict to quickly find the open socket:

send(sockets_by_ip[target_ip], data)

If the socket closes, getpeer() will no longer work.  This means I can't
do this:

del sockets_by_ip[closed_socket_object.getpeer()]

So I was going to use a mirror image dict to track the reverse relationship:

ip_by_sockets[Sx_object] = Sx_object.getpeer()

Now if the socket is closed for whatever reason, I can get the old IP
via this second dict and then purge:

old_ip = ip_by_sockets[closed_socket_object]
del sockets_by_ip[old_ip]
del ip_by_sockets[closed_socket_object]


The problem was that keying on the object itself wasn't working.  Using
the file descriptor had the same problem as the IP, it disappears if the
socket closes so I lose that relationship.  I was just trying to figure
out a way to get a 1-to-1 map of a socket object to some identifier that
is persistent.


More information about the Ale mailing list