get the IP address of a host

N

none

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.
 
K

Kartic

socket.gethostbyaddr(socket.gethostname())

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

Thanks,
--Kartic
 
L

Lee Harr

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).
 
J

J Berends

Lee said:
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.
 
N

Nick Coghlan

J said:
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.
 
P

P

J said:
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
 
J

Jorge Luiz Godoy Filho

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top