Python - How to get port of sender socket (UDP)

Viewed 7081

If I have a UDP socket like so:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

and the socket can send data:

sock.sendto("message", address)

How do I find out the port of the socket - the port used when sending data to address?

EDIT: I tried sock.getsockname() but this raises an error: [Errno 10022] An invalid argument was supplied

1 Answers

I'm not too familiar with the python socket class, but based on what I've read here https://docs.python.org/2/library/socket.html#socket.getnameinfo perhaps socket.getnameinfo()[1] might work

since .getsockname() returns a 2-tuple (host, port)

The socket must be bound before you can use .getsockname() by doing sock.bind(('', 0)).

Hope this helps!

Related