开发者

What is the second part of the address returned by recvfrom?

开发者 https://www.devze.com 2023-03-26 20:03 出处:网络
I\'m using those 2 pieces of code from http://wiki.python.org/moin/UdpCommunication The server: import socket

I'm using those 2 pieces of code from http://wiki.python.org/moin/UdpCommunication

The server:

import socket

UDP_IP="127.0.0.1"
UDP_PORT=5005

sock = socket.socket( socket.AF_INET, # Internet
                      socket.SOCK_DGRAM ) # UDP
sock.bind( (UDP_IP,UDP_PORT) )

while True:
    开发者_Go百科data, addr = sock.recvfrom( 1024 ) # buffer size is 1024 bytes
    print "received message:", data,"from", addr

The client:

import socket

UDP_IP="127.0.0.1"
UDP_PORT=5005
MESSAGE="Hello, World!"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE

sock = socket.socket( socket.AF_INET, # Internet
                      socket.SOCK_DGRAM ) # UDP
sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )

In the server, I modified the last line:

        print "received message:", data,"from", addr

so it prints the address that the message was sent from. On my macbook the port seems to be some random number between 40000 or 65000 (i'm just sure it seems random).

Any idea what this could be ?


It's an ephemeral port used by the client to send data to the server.


It definitely is the port. You can verify it on the sender side with print sock.getsockname().

You can as well set it deliberately with e. g. sock.bind(('', 54312)) before the sock.sendto() line.

This could be useful in context where software checks the port range of the sender: Ports 0..1023 are privileged ports - under many OSes only root is allowed to bind to these ports.

However, in the very most cases there is no point in changing it, so it mostly is better to leave it set the way it is.

This port has the meaning to be the 4th element of the tuple identifying a connection or counterpart of a connection. The tuple is (source_ip, source_port, destination_ip, destination_port).

0

精彩评论

暂无评论...
验证码 换一张
取 消