4

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
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
Vasudeva S
  • 125
  • 2
  • 11
  • That is exactly what it should return, it is by design, and not a bug. 127.0.0.1 is the loopback address of IPv4. 192.168.1.101 is your ethernet address, which is then translated into a public address by your router. Your are not using the correct way to get your ethernet address. – Ξένη Γήινος May 21 '22 at 17:19
  • Could you add your operating system? It might be a duplicate of - https://stackoverflow.com/questions/55296584/getting-127-0-1-1-instead-of-192-168-1-ip-ubuntu-python – Liron Berger May 21 '22 at 17:25
  • I'm using macOS Monterey – Vasudeva S May 21 '22 at 18:04
  • @Thyebri oh okay. I guess i will have to re-refer the docs and try again. Thanks anyways – Vasudeva S May 21 '22 at 18:12
  • This code is just a waste of time and space. If you know that the server is running in the same host you can hardwire "127.0.0.1" without writing any of this code at all. – user207421 May 22 '22 at 10:35
  • @user207421 agreed, but for my use case, my server is going to be a Jetson Tx1 developer board serially connected via UART or Ethernet to the raspberry pi where data transfer happens. Now hardcoding the IP address would work but not that efficient is what i kinda felt. – Vasudeva S May 23 '22 at 15:31

2 Answers2

5

127.0.0.1 is localhost address, it is right. If you want your device's address do this:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
dod0lp
  • 84
  • 5
0

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.
Rob G
  • 673
  • 3
  • 10