ip address?

Skip Montanaro skip at pobox.com
Sat Jan 26 17:28:33 EST 2002


    Max> how can i get the internet ip address of my connected pc?

If you are directly connected to the net (no firewall for example), you can
use this:

    socket.gethostbyname(socket.gethostname())

If, on the other hand, you are living behind a firewall and want to know
what IP address the rest of the world thinks you are coming from, I think
you have to coax another site into telling you.  This works for me:

    #!/usr/bin/env python

    import smtplib, re, socket, os, sys

    s = smtplib.SMTP("mail.mojam.com")
    code, msg = s.helo()
    s.quit()
    mat = re.search("([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", msg)

    if mat is not None:
        print mat.group(1)
    else:
        print "IP address unknown"
        sys.exit(1)

I'd be interested in seeing how others have solved this problem.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list