pythonpython-3.xsocketspython-sockets

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

Solution

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