I'm trying to find out if my server (should be running on 127.0.0.1:5000
) is actually running. I'm trying to use psutil.net_connections()
to figure it out:
filter(lambda conn: conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())
This should give me the item corresponds to my server, and to check if I actually got something, I just check the len(tuple(...)))
. However, using the tuple(...)
gives me AttributeError: 'tuple' object has no attribute 'ip'
which I don't get, since the inner tuple (i.e. conn.raddr
does have an "ip" attr).
This happens also when looping regularly:
In [22]: for conn in psutil.net_connections():
...: if conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000:
...: break
...: else:
...: print('server is down')
BUT when using it like this, it works!
In [23]: a=psutil.net_connections()[0]
In [24]: a.raddr.ip
Out[24]: '35.190.242.205'
psutil version: 5.7.2
Not all raddr
have an ip
attribute. The documentation says:
raddr
: the remote address as a(ip, port)
named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple(AF_INET*)
or""
(AF_UNIX). For UNIX sockets see notes below.
So you should check that raddr
not empty before trying to access the ip
and port
attributes.
filter(lambda conn: conn.raddr and conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())