0

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:

  1. 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)

  2. How to overcome this issue and make sure i always get the correct IP Address?

  3. 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

Adiel
  • 1,203
  • 3
  • 18
  • 31
  • Did you perform sanity checks on the variables self.host_name etc? – Jason Chia Feb 07 '23 at 15:58
  • @JasonChia yes, in all our automations - we dump the hostName and hostIp variable. The hostname is always correct one (and not "localhost" for example) – Adiel Feb 08 '23 at 07:16
  • Well until you can reproduce your problem its going to be a real pain to diagnose. I can't reproduce it on my environment even with automated scripts.... – Jason Chia Feb 13 '23 at 09:01

0 Answers0