0

I have been trying to connect to a remote server with python socket for that I am using create_connection but when my client tries to connect to that server it shown this error

AttributeError: 'socket' object has no attribute 'create_connection'

Here is my code

    def _connect(self):
        print("Connecting to ",self.hostname,self.port)
        self.sock.create_connection((self.hostname, self.port))
        print("Connection successfull")

Hostname and port is initialized in Constructor

    def __init__(self, host, port, path, headers, method):
        self.host = host.decode('utf-8')
        self.hostname = socket.gethostbyname(self.host)
        self.port = port
        self.path = path.decode('utf-8')
        self.header = headers
        self.method = method.decode('utf-8')
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Host and port is parsed from urlparse library

def from_url(cls, url, header, method):
        """Construct a request for the specified URL."""
        res = urlparse(url)
        path = res.path
        if res.query:
            path += b'?' + res.query
        return cls(res.hostname, res.port or 80, path, header, method)
2
  • 1
    What's self.sock equal to? Commented Jul 13, 2020 at 8:41
  • @TomDanilov self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Commented Jul 13, 2020 at 9:12

1 Answer 1

2

create_connection is a function in the socket module, not a method of the socket.socket class.

Furthermore, create_connection returns a socket.socket instance, so rather than creating one in __init__, you should set self.sock to some "uninitialized" value (e.g. None) in __init__ and assign the new socket.socket instance in _connect:

Replace

def __init__(self, …):
    # …
    self.sock = socket.socket(…)

def _connect(self):
    # …
    self.sock.create_connection((self.hostname, self.port))

by

 def __init__(self, …):
     # …
     self.sock = None

 def _connect(self):
     # …
     self.sock = socket.create_connection((self.hostname, self.port))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.