UDP socket, need help setting sending port
Steve Horsley
steve.horsley at gmail.com
Thu Dec 22 15:19:48 EST 2005
Sells, Fred wrote:
> I'm using MSW XP Pro with Python 2.4 to develop but production will be Linux
> with Python 2.3. (could upgrade to 2.4 if absolutely necessary) I can also
> switch to Linux for development if necessary.
>
> I am writing some python to replace proprietary software that talks to a
> timeclock via UDP.
>
> The timeclock extracts the sending port from the UDP header and uses that
> for all response messages.
>
> I cannot find out how to set the sending port in the header. Windows XP
> appears to set an arbitrary port. I've been using ethereal to analyze
> network traffic and it seems that if I can set the sending port, I should be
> OK.
>
> I have been googling various combinations of "python udp ..." for the last
> two hours and have not found anything that addresses how to set the sending
> port. I'm guessing that this may be in setsockopt but don't see any
> parameters that "click".
Try binding the address ('',0) which means any address, any port
on this box. Then get the bound address with getsockname(). Below
is a copy of an interactive try-out...
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> s.bind(('',0))
>>> s
<socket._socketobject object at 0xb7d9ee0c>
>>> s.getsockname()
('0.0.0.0', 32775)
>>>
So in this case, port 32775 was chosen to bind to.
Steve
More information about the Python-list
mailing list