get the IP address of a host
Jp Calderone
exarkun at divmod.com
Thu Jan 6 09:09:00 EST 2005
On Thu, 06 Jan 2005 14:35:16 +0100, J Berends <j.p.t.j.berends@[n0sp4m].nl> wrote:
>
> 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]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('1.2.3.4', 56))
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.
Jp
More information about the Python-list
mailing list