Following the code from here I have got an IP address checker. However instead of outputting an IP address it outputs []
. Code:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", request.decode('utf-8'))
print("your IP Address is: ", theIP)
Expected output:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: 40.74.89.185
The IP address there is not mine and comes from HERE.
Real output:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: []
I have just copied from the website and then fixed the errors. What have I done wrong. Help please...
My python version is idle 3.8.
Turns out that your regex where wrong: I've updated the code and using requests get:
findall
will return a list of elements since you are get only one ip back just use [0]
from requests import get
import re
iphtml = get('http://checkip.dyndns.org').text
theIP = re.findall( r'[0-9]+(?:\.[0-9]+){3}', iphtml)
print(f"Your IP is: {theIP[0]}")
Your code updated:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r'[0-9]+(?:\.[0-9]+){3}', request.decode('utf-8'))
print("your IP Address is: ", theIP[0])