-2

Why does the python command print(socket.gethostbyname(socket.gethostname())) give:

192.168.1.4 on my laptop 127.0.1.1 on my Raspberry PI when they're both on the same local network, and the PI's IP address is a static 192.168.1.61?

Please be gentle, I'm a bit clueless on networking terminology and understanding :)

reggie
  • 97
  • 2
  • Why you need to use that command ? It just printed a local loopback ip of the pi – yagmoth555 Jul 02 '15 at 13:10
  • Outch with the -2. I don't need to use the command, just wondered about the differences it gives and why that might be. Sorry if it was off topic, I may have misunderstood what this particular stack exchange site was for. – reggie Jul 03 '15 at 09:23

1 Answers1

1

gethostbyname has been obsolete since getaddrinfo was introduced more than a decade ago. However neither of them are intended to be used to find the IP address of the host your software is running on.

In order to find the IP address of the host your software is running on, the simplest approach is to create a UDP socket and connect it to the remote address you want to communicate with.

import socket
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, 0)
s.connect(('2001:db8::', 53))
print s.getsockname()

On a host with multiple IP addresses this may produce different result depending on which remote address you specify in the code.

kasperd
  • 29,894
  • 16
  • 72
  • 122