Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 127.0.1.1 instead of 192.168.1.* ip ubuntu python

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
like image 538
Smack Alpha Avatar asked Nov 28 '22 00:11

Smack Alpha


2 Answers

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.

like image 112
JubinBlack Avatar answered Dec 06 '22 20:12

JubinBlack


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.

like image 33
sanooj Avatar answered Dec 06 '22 22:12

sanooj