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()
>>> print socket.gethostbyname(socket.gethostname())
>>> socket.gethostbyaddr(socket.gethostbyname(socket.gethostname()))
('', ['k172-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!