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

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



Solution 1:[1]

I like the requests package with http://ip.42.pl/raw

import requests
requests.get('http://ip.42.pl/raw').text

Solution 2:[2]

With requests module

import requests

public_IP = requests.get("https://www.wikipedia.org").headers["X-Client-IP"]
print public_IP

Solution 3:[3]

Try this:

import ipgetter
import requests

IP = ipgetter.myip()
url = 'http://freegeoip.net/json/'+IP
r = requests.get(url)
js = r.json()
print 'IP Adress: '         +   js['ip']
print 'Country Code: '      +   js['country_code']
print 'Country Name: '      +   js['country_name']
print 'Region Code: '       +   js['region_code']
print 'Region Name: '       +   js['region_name']
print 'City Name: '         +   js['city']
print 'Zip code: '          +   js['zip_code']
print 'Time Zone: '         +   js['time_zone']
print 'Latitude: '          +   str(js['latitude'])
print 'Longitude: '         +   str(js['longitude'])

Solution 4:[4]

You can just do this:

import requests
print requests.get("http://ipecho.net/plain?").text

Produces:

XX.XX.XXX.XXX

Solution 5:[5]

in python 2.7 it's just a code of 2 lines.

>>> import requests
>>print requests.get("http://ipconfig.in/ip").text

Solution 6:[6]

This is a way not to have to make a call to the internet:

Please let me know if this doesn't work, then I can update the answer (it works for ~10 servers of mine)

from subprocess import check_output
out = check_output("/sbin/ifconfig | awk '/inet / { print $2 }' | sed 's/addr://'", shell=True)
[x for x in out.decode().split() if not x == "127.0.0.1" and 
                                    not (x.startswith("172") and x.endswith("0.1"))]
["x.x.x.x.x"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HyperActive
Solution 2 Ahmed
Solution 3 Xavi Martínez
Solution 4 Rob
Solution 5 OneCricketeer
Solution 6 PascalVKooten