Python sockets/port forwarding

Viewed 27213

I've written server and client programs with Python.

Server.py

import socket

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

host = socket.gethostname()
port = 5555

sock.bind((host, port))

sock.listen(1)

conn, addr = sock.accept()

data = "Hello!"
data = bytes(data, 'utf-8')

conn.send(data)

sock.close()

Client.py on Linux

import socket

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

host = socket.gethostname()
port = 5555

sock.connect((host, port))

data = sock.recv(2048)

data = str(data, "utf-8")

print(data)

sock.close()

When I run the server and then the client on my local machine (a Linux Mint), it works correctly. I got "Hello!" in bash, and everything is fine. BUT when I ran my client program on another machine (a Windows 8) and ran it (previously I ran server on Linux, of course, and change IP address in client to my static Linux mint's IP) it says:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

client.py on Windows

import socket
    
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
host = "here is my static ip"
port = 5555
    
sock.connect((host, port))
    
data = sock.recv(2048)
    
data = str(data, "utf-8")
    
print(data)
    
sock.close()

I must say that I had done port forwarding in my router settings on port 5555. Earlier, I had done same thing to port 80 and my own site worked correctly, but now it doesn't work to 5555 with Python sockets! Why? I can't get it! And one more thing: I tried to change the port to 80 in my server and client files, but it didn't work too. PLease, help.

2 Answers

I was stuck with the same problem months ago and also wasn't able to do port forwarding. I found a way out of port forwarding Ngrock

For your information what Ngrock does is it is a useful utility to create secure tunnels to locally hosted applications using a reverse proxy. It is a utility to expose any locally hosted application over the web

For How To use it, please see the steps shown below :

If you are in Mac write this command in your terminal to download ngrock

brew install ngrok

For windows

choco install ngrok

After installing You need need to sign up on the Ngrok website
You will get your Ngrock authentication token then paste this command in the terminal

For Mac and Windows

ngrok config add-authtoken <token>

Now that Ngrock is all setup you can start a tunnel using

ngrok tcp <Your Port Number Used In Server.py>
ngrok tcp 5321

Note : Please Give the command inside the directory in which the Python Socket Server File in Located

That's it Your Socket can connect you any computer over the internet anywhere in the world

If You are still struggling to see the detailed explanation in this video
You can also refer ngrock documentation here

Related