469,338 Members | 7,976 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,338 developers. It's quick & easy.

get the IP address of a host

I want to determine the outside (non local, a.k.a. 127.0.0.x) ip
addresses of my host. It seems that the socket module provides me with
some nifty tools for that but I cannot get it to work correctly it seems.

Can someone enlightened show a light on this:

import socket
def getipaddr(hostname='default'):
"""Given a hostname, perform a standard (forward) lookup and return
a list of IP addresses for that host."""
if hostname == 'default':
hostname = socket.gethostname()
ips = socket.gethostbyname_ex(hostname)[2]
return [i for i in ips if i.split('.')[0] != '127'][0]

It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex
only retrieves the 127.0.0.x ip adresses of the local loopback. Does
someone has a more robust solution?

Targetted OS'es are Windows AND linux/unix.
Jul 18 '05 #1
7 21617
socket.gethostbyaddr(socket.gethostname())

will return a tuple containing fully qualified hostname, alternative
hostnames, ip addresses (>1 if multihomed).

Thanks,
--Kartic

Jul 18 '05 #2
or

socket.gethostbyname(socket.gethostname())

Jul 18 '05 #3
On 2005-01-05, none <""> wrote:
I want to determine the outside (non local, a.k.a. 127.0.0.x) ip
addresses of my host. It seems that the socket module provides me with
some nifty tools for that but I cannot get it to work correctly it seems.

Can someone enlightened show a light on this:

import socket
def getipaddr(hostname='default'):
"""Given a hostname, perform a standard (forward) lookup and return
a list of IP addresses for that host."""
if hostname == 'default':
hostname = socket.gethostname()
ips = socket.gethostbyname_ex(hostname)[2]
return [i for i in ips if i.split('.')[0] != '127'][0]

It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex
only retrieves the 127.0.0.x ip adresses of the local loopback. Does
someone has a more robust solution?

Targetted OS'es are Windows AND linux/unix.

I found that the socket solutions only work if your
DNS entries are correct ... which in my case was not
true. So I came up with this:
import commands
ifconfig = '/sbin/ifconfig'
# name of ethernet interface
iface = 'eth0'
# text just before inet address in ifconfig output
telltale = 'inet addr:'
def my_addr():
cmd = '%s %s' % (ifconfig, iface)
output = commands.getoutput(cmd)

inet = output.find(telltale)
if inet >= 0:
start = inet + len(telltale)
end = output.find(' ', start)
addr = output[start:end]
else:
addr = ''

return addr

Basically, it scrapes the output from ifconfig for the
actual address assigned to the interface. Works perfectly
on FreeBSD and Linux (given the correct configuration).
Jul 18 '05 #4
Lee Harr wrote:
I found that the socket solutions only work if your
DNS entries are correct ... which in my case was not
true. So I came up with this:
That is indeed correct, and even if the DNS entries are correct at times
it does not give the full list of IPs by gethostbyname or gethostbyaddr.
import commands
ifconfig = '/sbin/ifconfig'
# name of ethernet interface
iface = 'eth0'
# text just before inet address in ifconfig output
telltale = 'inet addr:'

...

Basically, it scrapes the output from ifconfig for the
actual address assigned to the interface. Works perfectly
on FreeBSD and Linux (given the correct configuration).


Nice way, have to device something for windows than.

From several approached I came up with the following code:

def getipaddr(hostname='default'):
"""Given a hostname, perform a standard (forward) lookup and return
a list of IP addresses for that host."""
if hostname == 'default':
hostname = socket.gethostname()
ips = socket.gethostbyname_ex(hostname)[2]
ips = [i for i in ips if i.split('.')[0] != '127']
if len(ips) != 0:
# check if we have succes in determining outside IP
ip = ips[0]
elif len(ips) == 0 and hostname == socket.gethostname():
# when we want to determine local IP and did not have succes
# with gethostbyname_ex then we would like to connect to say...

# google.com and determine the local ip address bound to the
# local socket.
try:
s = socket.socket()
s.connect(('google.com', 80))
print ('___ connecting to internet to determine local ip')
ip = s.getsockname()[0]
del s
except:
print ('*** cannot connect to internet in order to \
determine outside IP address')
raise Exception
if len(ip) != 0:
return ip
else:
print ('*** unable to determine outside IP address')
raise Exception

It returns the IP address with which it connects to the world (not lo),
might be a pvt LAN address or an internet routed IP. Depend on where the
host is.

I hate the google trick actually, so any suggestions to something better
is always welcome.
Jul 18 '05 #5
J Berends wrote:
Lee Harr wrote:
Basically, it scrapes the output from ifconfig for the
actual address assigned to the interface. Works perfectly
on FreeBSD and Linux (given the correct configuration).

Nice way, have to device something for windows than.


Use the same approach, but scrape the output of ipconfig instead. Use subprocess
to run the command in Python 2.4, or work something out with one of the popen
variants for earlier versions.

Cheers,
Nick.

--
Nick Coghlan | nc******@email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #6
P
J Berends wrote:
def getipaddr(hostname='default'): [snip]

It returns the IP address with which it connects to the world (not lo),
might be a pvt LAN address or an internet routed IP. Depend on where the
host is.

I hate the google trick actually, so any suggestions to something better
is always welcome.


Yes your IP is determined really by what you connect to.
So I did essentially the same as you.
For reference see getMyIPAddress() at the following:
http://www.pixelbeat.org/libs/PadSocket.c

Pádraig
Jul 18 '05 #7
Kartic, Quarta 05 Janeiro 2005 14:08, wrote:
socket.gethostbyaddr(socket.gethostname())

will return a tuple containing fully qualified hostname, alternative
hostnames, ip addresses (>1 if multihomed).

or

socket.gethostbyname(socket.gethostname())


None of these work with computers with more than one interface... They get
only one of them. It would be safer, then, to specify the desired
interface or use an alternative method.

--
Godoy. <go***@ieee.org>

Jul 18 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Jeff | last post: by
21 posts views Thread by Alexander N. Spitzer | last post: by
4 posts views Thread by Marc-André | last post: by
1 post views Thread by Brian Henry | last post: by
24 posts views Thread by Daniel Crespo | last post: by
7 posts views Thread by misha | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by Purva khokhar | last post: by
1 post views Thread by haryvincent176 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.