Suppose I create a UDP socket in python, and then send a message using:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (DEST_IP, DEST_PORT))
How do I find out which source port my message was send from?
(I do not want to bind my socket to any specific port. But how do I find out which source port was used to send the message?)
The first getsockname() doesn't appear to work, but the second does. So perhaps it doesn't get valid values until after the first transmission:
#!/usr/local/cpython-3.3/bin/python
import socket
MESSAGE = b"Hello"
DEST_IP = '127.0.0.1'
DEST_PORT = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(sock.getsockname())
sock.sendto(MESSAGE, (DEST_IP, DEST_PORT))
print(sock.getsockname())
HTH
Help on method getsockname:
getsockname(...) method of socket._socketobject instance
getsockname() -> address info
Return the address of the local endpoint. For IP sockets, the address
info is a pair (hostaddr, port).
If you don't bind a UDP socket, an automatic bind occurs when you first send or receive. So getsockname() after that will tell you the allocated port number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With