Sarthak Kaushik
Sarthak Kaushik

Reputation: 19

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

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)

Upvotes: 0

Views: 2377

Answers (1)

mkrieger1
mkrieger1

Reputation: 23144

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))

Upvotes: 2

Related Questions