Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print the local and remote address and port of a connected socket?

Tags:

python

sockets

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?

like image 282
1qazxsw2 Avatar asked Dec 20 '16 20:12

1qazxsw2


People also ask

How do I find my socket port number?

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening: struct sockaddr_in sin; socklen_t len = sizeof(sin); if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1) perror("getsockname"); else printf("port number %d\n", ntohs(sin.

Which method of the socket module allows you to send data to a given address?

We send data with the sendto method. UDP sockets use recvfrom to receive data. Its paremeter is the buffer size. The return value is a pair (data, address) where data is a byte string representing the data received and address is the address of the socket sending the data.

Which method of the socket module allows you to associate a host and a port with a specific socket?

bind() − This method binds the address (hostname, port number) to the socket.


2 Answers

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)
like image 68
Amber Avatar answered Oct 25 '22 00:10

Amber


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

like image 30
deepDeepSea Avatar answered Oct 24 '22 22:10

deepDeepSea