-1

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.connect(("127.0.0.1",80))
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)
server.bind(("0.0.0.0",80))
server.listen(5)


# 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
    client_socket.send("ACK!".encode())
    client_socket.close()

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

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

[*] Accepted connection from: 127.0.0.1:56400
[*] Received: TEST Message
Issam
  • 1
  • 4

1 Answers1

2

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.

Andrew
  • 2,057
  • 2
  • 16
  • 25