Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the public IP using python2.7?

Tags:

python

ip

How can I get the public IP using python2.7? Not private IP.

like image 447
Searene Avatar asked Feb 28 '12 11:02

Searene


People also ask

What is my public IP address?

Here's how to find the IP address on the Android phone:Go to your phone's settings. Select “About device.” Tap on “Status.” Here you can find information about your device, including the IP address.

How do you check a IP is public or private in Python?

netaddr is a Python library for representing and manipulating network addresses. IPAddress('input ip'). is_private() will return true if the input ip address private, else it will return false.


1 Answers

Currently there are several options:

  • ip.42.pl
  • jsonip.com
  • httpbin.org
  • ipify.org

Below are exact ways you can utilize each of the above.

ip.42.pl

from urllib2 import urlopen my_ip = urlopen('http://ip.42.pl/raw').read() 

This is the first option I have found. It is very convenient for scripts, you don't need JSON parsing here.

jsonip.com

from json import load from urllib2 import urlopen  my_ip = load(urlopen('http://jsonip.com'))['ip'] 

Seemingly the sole purpose of this domain is to return IP address in JSON.

httpbin.org

from json import load from urllib2 import urlopen  my_ip = load(urlopen('http://httpbin.org/ip'))['origin'] 

httpbin.org is service I often recommend to junior developers to use for testing their scripts / applications.

ipify.org

from json import load from urllib2 import urlopen  my_ip = load(urlopen('https://api.ipify.org/?format=json'))['ip'] 

Power of this service results from lack of limits (there is no rate limiting), infrastructure (placed on Heroku, with high availability in mind) and flexibility (works for both IPv4 and IPv6).

EDIT: Added httpbin.org to the list of available options.

EDIT: Added ipify.org thanks to kert's note.

like image 154
Tadeck Avatar answered Oct 08 '22 07:10

Tadeck