get the IP address of a host
J Berends
j.p.t.j.berends at [N0SP4M].nl
Thu Jan 6 08:35:16 EST 2005
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.
More information about the Python-list
mailing list