determining an assigned IP address
Donn Cave
donn at oz.net
Mon Jun 26 00:55:34 EDT 2000
Quoth Bill Tolbert <bill_tolbert at bigfoot.com>:
| I've just set up Linux with my cable modem and I'd like to use Python to
| help me launch remote X apps. I need to know the ip address assigned by
| my isp, but so far I'm striking out. gethostbyname_ex in the socket
| module returns the address I supplied when I thought it was static.
| Right now the only way I know to get the right address is to log into
| another machine and use who.
That's pretty close to what I'm going to recommend. You were probably
thinking there would be some function that returns the real address,
but alas, that takes a lot of horsing around with ifconfig ioctls and
isn't perfectly reliable even then. So make a connection. That will
establish an address if necessary, and it will use the IP address that
your routing configuration associates with the outside world, and that's
the one you want.
The trick is that you can quiz the socket connection directly for its
local address, with the getsockname() method. The only rough spot is
that you're dependent on some external host; I use my primary DNS
service address, on the theory that I'm already pretty heavily dependent
on it anyway. Code follows.
Donn Cave, donn at oz.net
------------------------------
from socket import SOCK_STREAM, AF_INET, socket
def local_addr():
s = socket(AF_INET, SOCK_STREAM)
s.connect((my_dns_server, 53))
my_addr, local_port = s.getsockname()
s.close()
return my_addr
print local_addr()
More information about the Python-list
mailing list