Neo
Neo

Reputation: 1269

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.

Upvotes: 1

Views: 4260

Answers (2)

Maxim
Maxim

Reputation: 4431

The TCP connection is being refused because the GCP Firewall is indeed blocking it. Therefore, you must create a firewall rule that opens the TCP port for Ingress connections.

By navigating to Firewall rules in the VPC network section of the GCP Console, you can create firewall rules or update existing ones.

One approach is to tag your GCE instance, and when creating the firewall rule, set the target to be this tag, and as for 'Source filters', the IP of the machine you're attempting to establish the connection from, or simply allow all IPs to connect with 0.0.0.0/0 as the source. Remember to specify the TCP port that needs to be opened.

Upvotes: 3

John Hanley
John Hanley

Reputation: 81336

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.

Upvotes: 5

Related Questions