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

烂漫一生 提交于 2019-12-24 19:48:01

问题


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?


回答1:


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.




回答2:


You don't create a socket here neither you bind it to any port. What socket.gethostbyname('google.com') does is translate a host name to IPv4 address format. The method .close() has effect in open connections.



来源:https://stackoverflow.com/questions/51613507/traceback-most-recent-call-last-file-line-1-in-attributeerror-module-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!