Skip to content


Obtenir son adresse IP publique en Python

Décidément le Python c’est balaise. Obtenir son IP publique consiste à faire ceci :

from urllib2 import urlopen
public_ip = urlopen('http://whatismyip.org').read()

C’est tout. Merci à whatismyip.org grâce à qui on a rien besoin de parser.

Le code plus propre :

#!/usr/bin/env python

import sys
from urllib2 import urlopen, URLError

def get_my_public_ip():
    ret = None

    try:
        ret = urlopen('http://whatismyip.org').read()

    except URLError, e:
        sys.stderr.write("N'a pas pu obtenir l'adresse IP publique - Erreur %d: %s\n" % (e.reason.args[0], e.reason.args[1]))
        sys.exit(1)

    return ret

print get_my_public_ip()
Partager :
  • Facebook
  • Twitter
  • Wikio FR
  • Google Bookmarks
  • Netvibes
  • Live
  • email
  • Print

Posted in Internet.

Tagged with .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.