Python UDP Socket Port Random, Despite Purpose

I have two simple Python files: client.py and server.py. The client simply sends the text that you enter to the server through a UDP socket.

The assigned and listened port 21567 , BUT ... reading the line:

print "\nReceived message '", data,"' from ", addr

addr appears in server.py as something similar to this: ('127.0.0.1', 60471)

Now I don’t understand why this seemingly random port is being reported, 60471 is random every time the script is run. Can anyone shed some light on this question, why doesn't it say 21567 as set in the code? Thanks!

The contents of the Python script file are as follows:

client.py

# Client program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg

# Send messages
while (1):
    data = raw_input('>> ')
    if not data:
        break
    else:
        if(UDPSock.sendto(data,addr)):
            print "Sending message '",data,"'....."

# Close socket
UDPSock.close()

server.py

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", data,"' from ", addr

# Close socket
UDPSock.close()
+3
2

60471 - , 21567 - . : IP- , . 32768 65535. addr .

, (.. IP- ), , , UDP/IP.

+4

, , - . , . , - - 80, , .

+2

Source: https://habr.com/ru/post/1726678/


All Articles