0
votes

Main machine running python3.8.0

Second machine python 3.7.5

I created a server socket on my main machine:

import socket 

HOST = '' 
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

and I also created a client socket on a second machine:

import socket

HOST = ''  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

My understanding is that if I run the server socket and then connect by running the client socket, my server socket should print : "connected by [client ip], [specified port]"

At the same time the client should print : "Received b'Hello, world'.

What happens is my server prints "connected by [server ip], [random port]" and client prints "Received b'Hello, world'".

My questions are:

  1. Why does the server print the server ip and not the client ip? And why is the port random if I specified the port?

  2. If my server socket is running, how can I send data from a connecting client socket to the server socket?

For example: x = 'random string'. Upon the client socket connecting, how do I send 'x' so that I receive it on the server side?

1

1 Answers

1
votes
  1. Computer just always use the random port to connect, that is normal. About why it print the server IP, that you wrong, there no reason to print the server IP, the server IP is 127.0.0.1. I think you have run both server and client on the same machine.

  2. Let's I provide you what have you do:

  3. SERVER <-----create the connection-----> CLIENT
  4. SERVER --------------------------------- CLIENT

    |\________________

    |There is a connection!|

  5. SERVER <----------Hello world----------- CLIENT
  6. SERVER -----------Hello world----------> CLIENT
  7. SERVER --------------------------------- CLIENT

                          _____________________/|
    
                         |Received 'Hello world'|
    

That why your client print 'Hello world', not server. Look at this:

Server

with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024) # The server has received 'Hello world'
            if not data:
                break
            conn.sendall(data) # The server has sent back 'Hello world'

Client:

s.connect((HOST, PORT)) # Connected
s.sendall(b'Hello, world') # Send 'Hello world' 
data = s.recv(1024) # The server has received it but sent back so now the client received again