Search code examples
pythonservergoogle-cloud-platformgoogle-compute-enginefirewall

Can't connect to my google cloud VM instance through tcp using python


Situation

I wrote a simple program in python. It's a simple socket chatting program. In my program, the client just connect to an address (ip, port) and send a message, while at this time the server is ready and receives the message and prints it. I can assure the program is correct, since I tried on my computer.

I have a VM instance on Google Cloud Platform, which I can operate through ssh, a simple way provided by google cloud. I can make sure the server is working.

Problem

I start a simple tcp server, python program on my google cloud server. Then I start my client program on my computer. But I get this error:

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

or equivalently in Chinese:

ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

How do I solve this problem and connect to my google cloud server?

I guess maybe the firewall refused my computer's connection, but have no idea how to solve it.


Solution

  • This error means that your program is not listening on 0.0.0.0 port XYZ.

    Check to see if your program is instead listening on localhost. If it is change to 0.0.0.0 which means all available networks. localhost means do not listen on any network interfaces and only accept connections from inside the computer.

    Then double check the port number.

    To see if you have something listening run this command (Linux): netstat -at

    Look for a line with your port XYZ.

    When you start your program, make sure that it does not error when creating the listener. If you are trying to use a port number below 1024, you will need to lauch the program with root privileges.