3

I have two scripts: server.py and client.py and I am trying to connect them globally. They are something like this:

server.py:

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("", 5050))

while True:
    conn, addr = server.accept()

client.py:

import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("[my public ip (don\'t want to give away)]", 5050))

When I run server.py, everything is fine. When I try to connect with client.py, I get the error message: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. I have Firewall turned off.

Also, I have tried these questions but did not solve the problem:
No connection could be made because the target machine actively refused it?
How to fix No connection could be made because the target machine actively refused it 127.0.0.1:64527
No connection could be made because the target machine actively refused it 127.0.0.1:3446
No connection could be made because the target machine actively refused it 127.0.0.1
Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

2 Answers2

2

In your bind instead of "" you should be writing "0.0.0.0" to get all connections. Also, if you run the server and the client on the same computer you should use "127.0.0.1" instead of your public IP address since the connection is being done in your own machine. If you run each in different computers you can use the computer's local IP address, again, no need for public IP address (you can find it with cmd- write IPCONFIG and it will be shown, most of the times it looks liks "192.168.x.x". I'll add codes that worked for me here for you to use:

server.py

import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 5050))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
client_name = client_socket.recv(1024)
what_to_send = 'Hello ' + client_name.decode()
client_socket.send(what_to_send.encode())
client_socket.close()
server_socket.close()

client.py

import socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.connect(('127.0.0.1', 5050))
name = input("Enter your name: ")
my_socket.send(name.encode())
data = my_socket.recv(1024)
print(data.decode())
my_socket.close()
Yuval
  • 108
  • 6
  • Thanks for the answer! However, I forgot to include in the question that I am trying to connect globally. Could you show me how I can do that? –  Sep 16 '20 at 17:23
-1

Did you port forward your local IP and TCP port on your router?

If you didn’t, you will need to log in to your router through 192.168.0.1(Depends on the setting on your router) and got to port forwarding and add a rule (for my router) stating your local IP for your server and TCP port 5050(from your code) and save it.