Trying to get host-IP Through Python, using socket module - Occasionally, i get address 127.0.0.1 and not the real IP Address - i.e 10.210.24.24
I've adjusted my code per the answer in:
Socket IO returns 127.0.0.1 as host address and not 192.168.0.* on my device
But still get random encounters of 127.0.0.1.
The issue occurs in automation - Which SSH's into the remote host (10.210.24.24 for example), And runs the below code snippet.
Trying to reproduce manually - i always get the correct IP Address.
My code is as follows:
self.host_name = socket.gethostname()
try:
host_ip = socket.gethostbyname(self.host_name)
if host_ip == "127.0.0.1":
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
host_ip = s.getsockname()[0]
self.host_ip = host_ip
except Exception as e: # In case DNS Resolving fails
logger.warning("Failed setting '%s' IP | %s", self.host_name, str(e))
self.host_ip = ""
I'm trying to understand what am I missing here:
Why would "randomly", i would get 127.0.0.1 instead of the actual host IP. Given the fact the host definitely has IP Assigned (Since i'm using SSH root@ in order to run the script)
How to overcome this issue and make sure i always get the correct IP Address?
In case more debug info is needed - What logs should i look into once this issue does occur? I can add "fail handling" to at least dump those logs when the issue occurs in my automation.
System is Debian 11, Python 3.9.
Thanks