views:

445

answers:

2

Hi guys!

I have two simple Python files: client.py and server.py. The client simply sends the text you type to the server, via UDP socket.

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

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

in server.py outputs the addr to be something looking like this: ('127.0.0.1', 60471)

Now I don't understand why this seemingly random port is reported, the 60471 is random everytime the script is run. Can anyone please shed some light on this matter, why is it not saying 21567 like set in the code? Thanks!

The Python script file contents 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()
+4  A: 

60471 is the client's port and 21567 is the server's port. They can't be the same: Any IP traffic has to declare its source address and port, and its destination address and port. The client port is usually a random number in the range 32768 to 65535. addr is telling you the client's address.

This is done so you can have multiple clients talking to the same server (i.e. IP address and port combination), and the streams can be disambiguated using the client port numbers, even with a connectionless protocol like UDP/IP.

Mike D.
Cool! So everything is working like it should in other words!
Joe Zephyr
Actually, the client and server ports CAN be the same. It's irrelevant if they are, though, unless the server has specific requirements for the client port (e.g. for security purposes).
ΤΖΩΤΖΙΟΥ
+2  A: 

The port you are printing is that of the sender. The client's port is always random, stardard operating system mechanism. Just like a web server's port is 80, but when your computer connects to a server, you exit with a random port every time.

Am
The client's port is **NOT** always random. There's a reason that `bind` and `listen` are two separate calls; only "server" sockets listen, but both "client" and "server" ports can be bound.
ΤΖΩΤΖΙΟΥ
true, but in his code snipplet, the port is random.
Am