473,387 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 22033
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Jeff | last post by:
Is there a way to echo back a case sensitive $HTTP_HOST in PHP? For example if I type HostName.domain.com in my browser I want to return it exactly as it appears in the location part of the browser...
21
by: Alexander N. Spitzer | last post by:
If I have a machine with 3 virtual IP addresses (192.168.1.), how can I start 3 instances of the same RMI application (each started with different properties/configs), each listening on the port...
4
by: Marc-André | last post by:
I would like to find a simple way to test if a computer is online. I found a lot of code on internet about using existing ping class...but the code was not looking really good. There must be a...
1
by: Brian Henry | last post by:
How do you get information about the host computer? like IP address, host name, browser version, stuff like that. thanks!
24
by: Daniel Crespo | last post by:
Hi, I tried: import ctypes import socket import struct def get_macaddress(host): """ Returns the MAC address of a network host, requires >= WIN2K. """
7
by: misha | last post by:
Hello. I was wandering if someone could explain to me (or point to some manual) the process of mapping the addresses of host variables by DB2. Especially I would like to know when DB2 decides to...
5
by: Hooyoo | last post by:
Hi, here, How to get local machine name and IP address? Thanks.
2
by: martin lanny | last post by:
Simple network scanner is a part of my dotnet solution. It pings ip addresses in a selected network range and gives me the response time for each computer it finds. Anyhow, I would need to...
0
by: eddiefisher41 | last post by:
Hi guys. Im having a little trouble with one of my phyon cgi scripts. Basically i need to a function that runs on the server size as a python cgi script but returns the IP address of the web...
0
by: sganeshsvk | last post by:
sir, In Linux, We use send mail from some specific client host IP address to main server by using postfix configuration. Suppose Some unwanted users or other third persons hosts send the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.