Name or service unknown

I am trying to get the ipaddress of a person who is logged in using the code below, but I am getting an 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 another linux block. Not sure if I fix it.

+4
source share
3 answers

The error occurred only due to an incorrect host name setting. Set the host name in three different places:

  • / etc / hostname
  • / etc / hosts
  • run the command $ hostname

then log out again and log in. You are done.

+1
source

, socket.gethostname(), , . . /etc/hosts, , . , , , , , .

0

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

Instead, you can use this command, which tries to connect to the Google DNS server on 8.8.8.8 on 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])
0
source

All Articles