How do I print the local and remote address and po

2020-06-09 08:11发布

问题:

I have a connected socket. When I use:

print (mySocket)

I get this:

<socket.socket fd=376, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.31.244', 4160), raddr=('192.168.31.244', 7061)>

I can also successfully print:

print (mySocket.family)
print (mySocket.proto)

But if I try to print the address:

print(mySocket.laddr)

I get and error:

AttributeError: 'socket' object has no attribute 'laddr'

How can I print the laddr and raddr attributes?

回答1:

Try using the .getsockname() and .getpeername() methods instead. As noted in the Socket object docs only the family, proto, and type fields are available as attributes.

>>> s.bind(('localhost',12345))
>>> s.getsockname()
('127.0.0.1', 12345)


回答2:

For laddr use mySocket.getsockname() and for raddr use mySocket.getpeername()