any ideas??
THanks
On Windows, this works:
socket.gethostbyname(socket.gethostname())
Is that OK on real operating systems too?
--
Cheers,
Simon B,
si...@brunningonline.net,
http://www.brunningonline.net/simon/blog/
To get the public IP (like when you're behind a wirless router, etc) you
may try doing something like this:
import urllib
import re
import time
ip_search = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
try:
f = urllib.urlopen("http://www.ipchicken.com")
data = f.read()
f.close()
current_ip = ip_search.findall(data)
if current_ip:
print current_ip
time.sleep(3)
except Exception:
pass
HTH,
rbt
I use the following (all on one line):
external_ip = os.popen("/sbin/ifconfig eth0|/bin/grep inet|/bin/awk
'{print $2}' | sed -e s/.*://", "r").read().strip()
Cheers,
Andy
> On 15 Apr 2005 06:03:06 -0700, codecraig <code...@gmail.com> wrote:
> > hi,
> > how can i use python to figure the ip address of the machine which
> > the python script is running on? I dont mean like 127.0.0.1....but i
> > want the external IP address (such as ipconfig on windows displays).
>
> On Windows, this works:
>
> socket.gethostbyname(socket.gethostname())
>
> Is that OK on real operating systems too?
It will work sometimes, but there is nothing I know of
that specifically distinguishes "the" external network.
If you want something that reliably finds a network that
will be used for a certain type of connection, then the
best thing to do is make a connection like that, and
inspect the results. The getsockname() method shows the
IP address.
Donn Cave, do...@u.washington.edu
I use this:
#conf.py
ifconfig = '/sbin/ifconfig'
iface = 'eth0'
telltale = 'inet addr:'
#addr.py
import commands
from conf import ifconfig, iface, telltale
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 = ''
onti...@tenup.com writes:
> codecraig ha scritto:
>> how can i use python to figure the ip address of the machine which
>> the python script is running on? I dont mean like 127.0.0.1....but i
>> want the external IP address (such as ipconfig on windows displays).
>
That won't work if you're on a NAT'ed network - it will instead return
the external address of the NAT gateway. ipconfig displays the ip
address(es) of the interfaces on the current machine.
You need to use the socket.socket.getsockname method:
py> import socket
py> s = socket.socket()
py> s.connect(("google.com", 80))
py> s.getsockname()
('192.168.1.1', 57581)
py>
The local ethernet card is 192.168.1.1, the local port for the socket
is 57581.
Note that the presence of multiple interface cards makes the question
ambiguous.
<mike
--
Mike Meyer <m...@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.