1from requests import get
2
3ip = get('https://api.ipify.org').text
4print(f'My public IP address is: {ip}')
1# This example requires the requests library be installed. You can learn more
2# about the Requests library here: http://docs.python-requests.org/en/latest/
3
4from requests import get
5
6ip = get('https://api.ipify.org').text
7print 'My public IP address is:', ip
1# this is more faster solution written in python2 tho :D
2# comapre it with other solutions and you'll see
3
4import urllib2
5
6def get_public_ip(request_target):
7 grabber = urllib2.build_opener()
8 grabber.addheaders = [('Useragent','Mozilla/5.0')]
9 try:
10 public_ip_address = grabber.open(target_url).read()
11 except urllib2.HTTPError, error:
12 print("There was an error trying to get your Public IP: %s") % (error)
13 except urllib2.URLError, error:
14 print("There was an error trying to get your Public IP: %s") % (error)
15 return public_ip_address
16
17public_ip = "None"
18target_url = "http://ip.42.pl/raw"
19public_ip = get_public_ip(target_url)
20
21if not "None" in public_ip:
22 print("Your Public IP address is: %s") % (str(public_ip))
23else:
24 print("Your Public IP address was not found")