Getting 127.0.1.1 instead of 192.168.1.* ip ubuntu python

Question:

I am new to python. I want to get the ipaddress of the system. I am connected in LAN. When i use the below code to get the ip, it shows 127.0.1.1 instead of 192.168.1.32. Why it is not showing the LAN ip. Then how can i get my LAN ip. Every tutorials shows this way only. I also checked via connecting with mobile hotspot. Eventhough, it shows the same.

import socket    
hostname = socket.gethostname()    
IPAddr = socket.gethostbyname(hostname)    
print("Your Computer Name is:" + hostname)    
print("Your Computer IP Address is:" + IPAddr)    

Output:

Your Computer Name is:smackcoders
Your Computer IP Address is:127.0.1.1

Required Output:

Your Computer Name is:smackcoders
Your Computer IP Address is:192.168.1.32
Asked By: Smack Alpha

||

Answers:

This solution works for me on Windows. If you’re using Linux you could try this line of code instead:

IPAddr = socket.gethostbyname(socket.getfqdn())
Answered By: Remy

How can I get the IP address of eth0 in Python?

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print s.getsockname()[0]
Answered By: Sativa

As per the above ‘/etc/hosts’ file content, you have an IP address mapping with ‘127.0.1.1’ to your hostname. This is causing the name resolution to get 127.0.1.1. You can try removing/commenting this line and rerun.

Answered By: sanooj

I got this same problem with my raspi.

host_name = socket.gethostname()`
host_addr = socket.gethostbyname(host_name)

and now if i print host_addr, it will print 127.0.1.1.
So i foundthis: https://www.raspberrypi.org/forums/viewtopic.php?t=188615#p1187999

host_addr = socket.gethostbyname(host_name + ".local")

and it worked.

Answered By: JubinBlack

i get the same problem what your are facing. but I get the solution with help of my own idea, And don’t worry it is simple to use.
if you familiar to linux you should heard the ifconfig command which return the informations about the network interfaces, and also you should understand about grep command which filter the lines which consist specified words
now just open the terminal and type

ifconfig | grep 255.255.255.0

and hit enter now you will get wlan inet address line alone like below

inet 192.168.43.248  netmask 255.255.255.0  broadcast 192.168.43.255

in your terminal
in your python script just insert

#!/usr/bin/env python
import subprocess
cmd = "ifconfig | grep 255.255.255.0"
inet = subprocess.check_output(cmd, shell = True)
inet = wlan.decode("utf-8")
inet = wlan.split(" ")
inet_addr = inet[inet.index("inet")+1]
print(inet_addr)

this script return your local ip address, this script works for me and I hope this will work for your linux machine
all the best

Answered By: Marimuthu

This also worked for me:

gethostbyname(gethostname()+'.')
Answered By: Bruce