问题
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 -
- /etc/hostname
- /etc/hosts
- 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