Skip to main content

python code for querying own IP address

The socket.gethostname() function is supposed to give the IP address of the machine but it may not give the real IP address but gives 127.0.0.1. Even it is said that removing 127.0.0.1 from the /etc/hosts file (in ubuntu) can give the real IP but it could not help in my case.

import socket

nodeName = socket.gethostname()
info = socket.getaddrinfo(nodeName, None, 0, socket.SOCK_STREAM)
print [x[4][0] for x in info]   # prints 127.0.0.1
I came through another way which can print the real IP as well:


import commands
NodeIPS = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +
                         "awk {'print $2'} | sed -ne 's/addr\:/ /p'")
print NodeIPS  # prints 127.0.0.1 and realIP(eg. 202.145.12.22)
Note: code worked for ubuntu 12.04 and python 2.7

Sometimes its handy to have the IP address as list items. The following code does the work.
import os
listIPs=[]
f=os.popen("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " + "awk {'print $2'} | sed -ne 's/addr\:/ /p'")
for i in f.readlines():
listIPs.append(i.rstrip('\n'))
print listIPs

Comments