0

I tried multiple options for Python 3 given in the following thread to get the machine's external IP:

Getting a machine's external IP address with Python

import urllib.request
from socket import timeout
import os
import json

external_ip = urllib.request.urlopen('https://ident.me', timeout=10).read().decode('utf-8')
print(external_ip)

externalIP  = os.popen('curl -s ifconfig.me').readline()
print(externalIP)

data = json.loads(urllib.request.urlopen("http://ip.jsontest.com/").read())
print (data["ip"])

When I open the links in browser - https://ident.me, http://ipconfig.me and http://ip.jsontest.com they are giving different IP (same for the 3 external services) than what is showing up on the screen (my internal IP). What could be causing this issue? I am using a proxy app which changes the external IP and wanted to use it for proxy in script.

Raul R
  • 1
  • 1
  • First off, the [`requests`](https://requests.readthedocs.io/) library is your friend. Next could you try and clarify that paragraph where you ask the question at the end? Like what is the specific network environment you are working (e.g. computer -> router -> proxy -> internet? etc.). Maybe, give specific examples with filler IP addresses like w.x.y.z and a.b.c.d. – Kevin Jun 09 '20 at 16:58
  • The proxy settings from tbe browser obviously don't seem to affect python, so how did you set up that proxy? What browse and OS are you using? The default way to set up a proxy for python would be to set the `http_proxy` and `https_proxy` environment variables - see: https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies and https://docs.python.org/3/library/urllib.request.html#urllib.request.ProxyHandler – mata Jun 09 '20 at 17:02
  • Computer (Windows 10 OS) -> Wifi Router->Proxy -> Internet is the setup. I am using the Chrome/Firefox Browser. The proxy is being setup by a Windows App (with authentication similar to a VPN). I am trying to read the proxy IP first before setting up the proxy for python. That's where the issue lies. I am not able to read it correctly. – Raul R Jun 09 '20 at 17:41
  • The external services are showing IP as 1.1.1.1 in browser while in the script output it is showing 2.2.2.2 (internal IP without the proxy) – Raul R Jun 09 '20 at 17:51

1 Answers1

0

After spending lot of time experimenting with solutions, with inputs from @Kevin and @mata, I finally have come with the answer. Thanks Kevin and Mata, your help is greatly appreciated.

Here is the workaround for the problem:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://ident.me")
elem = driver.find_element_by_tag_name('pre')
element_text = elem.text
print (element_text)

driver.close()

Now it is returning the same IP as the browser by emulating the browser and then scraping it instead of directly using the requests.

Raul R
  • 1
  • 1