I'm new to network programming and I'm starting simple. I got 2 simple python scripts both running on my machine, a server and a client, the client sends some data using the port 80 and the server listens on the port 80 and prints the data and answer with a simple "ACK", and it works. But when the server receives the data it gets it from a random port. However if I change the sending port on the client or the listening one on the server, it stops working. I dont understand how it works.

This is the client script

import socket
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.send("TEST Message".encode())
r = c.recv(200)
print (r.decode())

And this is the server

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# this is our client-handling thread
def handle_client(client_socket):
    # print out what the client sends
    request = client_socket.recv(1024)
    print ("[*] Received: %s" % request.decode())
    # send back a packet

while True:
    client,addr = server.accept()
    print ("[*] Accepted connection from: %s:%d" % (addr[0],addr[1]))
    # handle incoming data

and this is the anwser of the server when running the client

[*] Accepted connection from:
[*] Received: TEST Message

closed as off-topic by joeqwerty, Michael Hampton Mar 26 '18 at 22:21

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on Server Fault must be about managing information technology systems in a business environment. Home and end-user computing questions may be asked on Super User, and questions about development, testing and development tools may be asked on Stack Overflow." – Michael Hampton
If this question can be reworded to fit the rules in the help center, please edit the question.


All TCP/IP communications use two separate ports for communicating.

When a device or client sends data, it uses an Ephemeral Port (typically greater than 1024, but usually even higher) for the Source Port, but is destined for the Service Port. In your example, the service port is HTTP services on Port 80, so all TCP traffic destined for this service goes to port 80. But when the client SENDS data, it uses something high, in this instance, 56400. The TCP transaction here can be described as the connection W.X.Y.Z:56400 <--> S.R.V.R:80. This allows the server to send data back to the client on that Ephemeral Port (56400 in this case)

This is just part of how TCP/IP works.

Not the answer you're looking for? Browse other questions tagged or ask your own question.