[Tutor] IP Address from Python module?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 8 03:05:23 CEST 2005



> >I think you're looking for socket.gethostbyname().
> >
> >    http://www.python.org/doc/lib/module-socket.html#l2h-2594
> >
> >Here's an example using the socket.gethostbyname() function:
> >
> >    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890
> >
> >
> Oh.. btw I don't think that will work on the internet. Cause a friend of
> mine has the 192.168.0.2 IP.


Hi Joe,

That actually sounds right in a sense.  Any internet address with
'192.168.x.x' is a "local" IP address, and is commonly allocated to folks
on an internal network.  For the really dull details about this, see RFC
1918 on "Private Address Space":

    http://www.faqs.org/rfcs/rfc1918.html

So anything with 192.168.x.x is a private, internal address.  In the
context of the Internet, it's sorta useless, since it's not an address
that one can use to connect to an external machine outside of the local
area network.

In fact, Brian Hammon's comment in:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890

does mention that if you're behind a router, then the router itself sets
up a small private network, which may explain why you may be seeing
'192.168.x.x' as an address.

The second comment on the cookbook page shows an alternative technique
that should be more robust: use http://checkip.dyndns.org.



> My internet IP should be IPv6 and I don't think it changes...

Are you sure about that?  IPv6 has not been widely deployed yet; most
folks still connect to the internet through the IPv4 protocol.

On the off-chance that you ARE on IPv6, see the getaddrinfo() function,
which should accomodate:

    http://www.python.org/doc/lib/module-socket.html#l2h-2592

For example:

######
>>> import socket
>>> socket.getaddrinfo('hkn.eecs.berkeley.edu', 80)
[(2, 1, 6, '', ('128.32.47.228', 80)),
 (2, 2, 17, '', ('128.32.47.228', 80))]
######


Good luck to you!



More information about the Tutor mailing list