'Socket IO returns 127.0.0.1 as host address and not 192.168.0.* on my device

When I run the following code to determine my device's local IP address, I get 127.0.0.1 instead of 192.168.0.101.

import socket
import threading

PORT = 8080
HOST_NAME = socket.gethostname()
print(HOST_NAME)
SERVER = socket.gethostbyname(HOST_NAME)

print(SERVER)

The output i get on the console is

MyDeviceName.local
127.0.0.1


Solution 1:[1]

Try this:

NOTE - Tested on CentOS 7.9 using Python 3.6.8, and Ubuntu 20.04 using Python 3.8.10

NOTE - You may have to install psutil when using Ubuntu 20.04

import socket

import psutil

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
my_eip = s.getsockname()[0]
nics = psutil.net_if_addrs()
my_enic = [i for i in nics for j in nics[i]
           if j.address == my_eip and j.family == socket.AF_INET][0]
print('My Ethernet NIC name is {0} and my IPv4 address is {1}.'.format(
    my_enic, my_eip))

Output:

My Ethernet NIC name is enp0s3 and my IPv4 address is 192.168.0.101.

Solution 2:[2]

Think of it from a high level, you are building your Vue application into a static website. Static websites only require a simple HTTP server. Therefore you can host and test this production build two different ways:

  1. With a simple local HTTP server (apache, nginx, node express), or you could use something like https://www.npmjs.com/package/http-server

  2. Host your production build online somewhere, such as https://pages.github.com/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob G
Solution 2 Nathan