Friday, August 14, 2009

Get your ip address in python


Python socket module provides the following functions you can get the IP address of your machine.


>>> import socket
>>> print socket.gethostname()
k172-16-0-12.heo.unstableme.com
>>> print socket.gethostbyname(socket.gethostname())
172.16.0.12
>>> socket.gethostbyaddr(socket.gethostbyname(socket.gethostname()))
('k172-16-0-12.heo.unstableme.com', ['k172-16-0-12'], ['172.16.0.12'])


Few definitions:

gethostbyname (hostname)
Translate a host name to IP address format. The IP address is returned as a string

gethostname ()
Return a string containing the hostname of the machine where the Python interpreter is currently executing. If you want to know the current machine's IP address, use socket.gethostbyname(socket.gethostname()). Note: gethostname() doesn't always return the fully qualified domain name; use socket.gethostbyaddr(socket.gethostname())

gethostbyaddr (ip_address)
Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IP addresses for the same interface on the same host (most likely containing only a single address). To find the fully qualified domain name, check hostname and the items of aliaslist for an entry containing at least one period.

Read more about Built-in Module socket here

Another link to "Determine the IP address of an eth interface"

1 Comment:

Ken Thompson said...

Nicely described. Thanks!