Search code examples
pythonsocketsnetwork-programminggethostbyname

Traceback (most recent call last): File "", line 1, in AttributeError: module 'socket' has no attribute 'close'


I need to write a program that retrieves the IP addresses of a list of domain names. The simple example can be shown here:

>>> import socket
>>> socket.gethostbyname('google.com')
'172.217.160.14'
>>> socket.close()

After I try to close the socket, I get this error:

Traceback (most recent call last): File "", line 1, in AttributeError: module 'socket' has no attribute 'close'

How can I close this socket? I need to close it because my actual program has loop where in each domain name in the list I needs to get its IP, so I need to close the socket in each iteration for the new host.

Can you tell me what is the problem?


Solution

  • The socket in your code refers to the socket module, which has no close function. A new module level close function has been added in Python 3.7, but it requires a socket descriptor as an argument. If I get it right, you want to call the close method of socket object, not the module. In your case you don't need to close any connection.