6

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.

user1050619
  • 19,822
  • 85
  • 237
  • 413

3 Answers3

4

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.

Yogesh Jilhawar
  • 5,605
  • 8
  • 44
  • 59
0

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.

woot
  • 7,406
  • 2
  • 36
  • 55
0

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])
Maryam Homayouni
  • 905
  • 9
  • 16