473,799 Members | 2,927 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(hostn ame='default'):
"""Given a hostname, perform a standard (forward) lookup and return
a list of IP addresses for that host."""
if hostname == 'default':
hostname = socket.gethostn ame()
ips = socket.gethostb yname_ex(hostna me)[2]
return [i for i in ips if i.split('.')[0] != '127'][0]

It does not seem to work on all hosts. Sometimes socket.gethostb yname_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 22097
socket.gethostb yaddr(socket.ge thostname())

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

Thanks,
--Kartic

Jul 18 '05 #2
or

socket.gethostb yname(socket.ge thostname())

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(hostn ame='default'):
"""Given a hostname, perform a standard (forward) lookup and return
a list of IP addresses for that host."""
if hostname == 'default':
hostname = socket.gethostn ame()
ips = socket.gethostb yname_ex(hostna me)[2]
return [i for i in ips if i.split('.')[0] != '127'][0]

It does not seem to work on all hosts. Sometimes socket.gethostb yname_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.getout put(cmd)

inet = output.find(tel ltale)
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(hostn ame='default'):
"""Given a hostname, perform a standard (forward) lookup and return
a list of IP addresses for that host."""
if hostname == 'default':
hostname = socket.gethostn ame()
ips = socket.gethostb yname_ex(hostna me)[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.gethostn ame():
# when we want to determine local IP and did not have succes
# with gethostbyname_e x 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(('goo gle.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(hostn ame='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.gethostb yaddr(socket.ge thostname())

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

or

socket.gethostb yname(socket.ge thostname())


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
3348
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 "HostName.domain.com" but it keeps returning a case insensitive result "hostname.domain.com".
21
15733
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 1234, but each instance binds to a different ip address. that is to say: instance #1 binds to 192.168.1.5/port 1234 instance #2 binds to 192.168.1.6/port 1234 instance #3 binds to 192.168.1.7/port 1234
4
8757
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 simple way to do that? Thanks!
1
1603
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
7328
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
13714
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 reinitialize the addresses and even more when it decides not to do it. Recently I've ben strucked with a problem of host variables defined in LINKAGE SECTION, and it took me some time to find the cause and solution for the problem.
5
72357
by: Hooyoo | last post by:
Hi, here, How to get local machine name and IP address? Thanks.
2
4765
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 retrieve two more pieces of information for each active (local network) IP address: - Computer's Host Name - Mac Address
0
2303
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 based user on the website. I then use the IP as an ideantifier for some other processes and data logging. The script i have is: def getIP(): """Get host IP address""" IP = socket.gethostbyname(socket.gethostname())
0
1828
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 mail to main server then their IP address was blocked by using postfix configuration. But,I want How to send the mail to main server from third persons host IP address or any other host machine IP address then it is possible, by using Postfix How...
0
9687
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10482
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10251
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10225
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7564
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.