Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which port is being used by my socket

Tags:

python

sockets

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?)

like image 507
hrs Avatar asked Nov 24 '25 13:11

hrs


2 Answers

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).
like image 111
dstromberg Avatar answered Nov 26 '25 01:11

dstromberg


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.

like image 33
user207421 Avatar answered Nov 26 '25 03:11

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!