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

I use these 2 pieces of code from http://wiki.python.org/moin/UdpCommunication

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: data, addr = sock.recvfrom( 1024 ) # buffer size is 1024 bytes print "received message:", data,"from", addr 

Customer:

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

On the server, I changed the last line:

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

so that it prints the address from which the message was sent. On my macbook, the port seems to be a random number between 40,000 or 65,000 (I'm just sure it seems random).

Any idea what this could be?

+4
source share
2 answers

This is the ephemeral port used by the client to send data to the server.

+3
source

This is definitely a port. You can check it on the sender side with print sock.getsockname() .

You can also install it using e. d. sock.bind(('', 54312)) before the line sock.sendto() .

This can be useful in a context where the software checks the sender port range: ports 0..1023 are privileged ports - in many operating systems only root allowed to communicate with these ports.

However, in most cases it makes no sense to change it, so it is better to leave it as it is.

This port has the value of the 4th element of the tuple identifying the connection or copy of the connection. Tuple (source_ip, source_port, destination_ip, destination_port).

+1
source

All Articles