Question

How to open a specific port for python-socket service?

Posted May 23, 2019 1.2k views
Getting Started DigitalOcean Python Networking Firewall Ubuntu 16.04 DigitalOcean Cloud Firewalls

I’m trying to run a simple python server on my droplet, with the python script below, and it works fine on my friend’s alicloud server. I guess it was the port I used was not configed correctly, but found out the firewall in ubuntu was not enabled. So i added some new rules to the cloud firewall to open the port 8005(which i intend to ues), but it still doesn’t work. Can anyone tell me how to config this?

# coding:utf-8

import socket

from multiprocessing import Process


def handle_client(client_socket):

    request_data = client_socket.recv(1024)
    print("request data:", request_data)

    response_start_line = "HTTP/1.1 200 OK\r\n"
    response_headers = "Server: My server\r\n"
    response_body = "<h1>Python HTTP Test</h1>"
    response = response_start_line + response_headers + "\r\n" + response_body


    client_socket.send(bytes(response, "utf-8"))


    client_socket.close()


if __name__ == "__main__":
    name=socket.gethostname()
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((name, 8005))
    server_socket.listen(128)

    while True:
        client_socket, client_address = server_socket.accept()
        print("[%s, %s]user connected" % client_address)
        handle_client_process = Process(target=handle_client, args=(client_socket,))
        handle_client_process.start()
        client_socket.close()

and here’s the errorcode: ConnectionRefusedError: [WinError 10061]
thx a lot!!!

1 comment

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

1 answer

Hello, @VEWOXIC

You can either enable it and use or just use iptables to open the port. Basically it’s totally up to you, but UFW’s syntax is easier to use.

Let me know if you have any questions.

Regards,
Alex

Submit an Answer