Name or service not known

纵饮孤独 提交于 2020-01-03 13:39:12

问题


I have been trying to get the ipaddress of the person who logged into the machine using the below code but I get a error.

>>> import socket
>>> socket.gethostbyname_ex(socket.gethostname())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known

The same code works in other linux box. Not sure I fix it.


回答1:


Error has occurred just because of not setting up hostname properly. Set the hostname at three different places, which are in -

  1. /etc/hostname
  2. /etc/hosts
  3. run command $ hostname

then logout and login again. You are done.




回答2:


Check what is being returned by socket.gethostname() and see if you can ping it. Basically this is a lookup failure. Check your /etc/hosts to see if it is listed. I know it seems strange, but I think if the hostname being returned does not have an entry, you'll get a name service failure which is what that is.




回答3:


If you are working with IPv6 or with servers with multiple network interfaces, this command will not work correctly.

Instead, you can use this command that tries to connect to the Google DNS server at 8.8.8.8 at port 53, and return your ip:

import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])


来源:https://stackoverflow.com/questions/38254394/name-or-service-not-known

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