I want to build a Python program to check the NSlookup result.
In my program, I want to output like:-
If I input google then it will show “not unique” as output, but
when I provide input like Rajat then the output will be unique because rajat.com is not a valid site (invalid URL no IP is linked with this URL)
Below is my code.in this code will show not unique when I input google but throw an error when I input Rajat.
So I just want to know how to handle this error or how we can get the output as unique when the program throws an error.
import socket
dns=input("Enter DNS: ")
result= socket.gethostbyname(dns+".com")
if not result:
print("Unique")
else:
print("Not Unique")
The gethostbyname() function raises the socket.gaierror exception if the given hostname is not found, so you have an opportunity to catch it and perform what you want:
import socket
dns=input("Enter DNS: ")
try:
result= socket.gethostbyname(dns + ".com")
except socket.gaierror:
print("Unique")
else:
print("Not Unique"))
Note:
In my humble opinion the better messages would be something as “Not used” / “Used” or
“Not found” / “Found”. Yours are a little confusing.
You can use try-except to catch an error. In this code snippet we try to connect to the given domain and if the connection is successful (the website exists) it prints Not unique, if not, it prints Unique.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = input("Enter DNS: ")
try:
s.connect((dns + ".com", 80))
except Exception as e:
print("Unique")
else:
print("Not unique")
Related
I have the following code:
while True:
try:
HOST = input(float(('Enter host IP'))
except ValueError:
print('Error. That is not a valid IP address.')
continue
I require the user to input an IP address. I wanted to set an error so that if he uses a letter he gets an error. How can I do that and why isn't my code working?
Try something like this
while True:
try:
HOST = input('Enter host IP: ')
if len(HOST.split(".")) != 4:
raise ValueError
for char in HOST:
if char not in "0123456789.":
raise ValueError
except ValueError:
print('Error. That is not a valid IP address.')
continue
else:
break
There is no need for the try/except. You just need an IP validation. This code should be working.
import re
while True:
HOST = input("Enter IP adress: ")
if re.match(
r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
HOST,
):
print(f"{inp} is valid IP adress")
break
else:
print("Enter valid IP adress")
I will begin by pointing out a few problems with your submitted code. First of all, your code will never exit the while loop, since you have provided no break out. Secondly, a valid IP address takes the form of something along the lines of 192.168.2.10 for IPV4 or "2001:0db8:0a0b:12f0:0000:0000:0000:0001" for IPV6, and which can never be interpreted as a float, so you will always generate a value error response. In order to validate an IP addfress correctly checkout the following check if a string matches an IP address pattern in python?.
import ipaddress
Host = None
while True:
try:
Host = ipaddress.ip_address(input('Enter host IP'))
break
except:
print('Error. That is not a valid IP address.')
continue
Currently I have a program that has proxies and makes a request to get my ip address with that proxy and returns it back in json.
An example request back is this:
Got Back: {'ip': '91.67.240.45', 'country': 'Germany', 'cc': 'DE'}
I want my program to try and make a request to the url and if it does not get the request because the proxy is down I want to try again 5 times before moving onto the next ip address.
I thought this except block would work but it is not breaking out of the loop when the 5 iterations are over and I am not sure why.
My program does however work when the proxy is up for the first try as it breaks after the first attempt and then moves onto the next ip address.
Here is what I currently have:
import requests
import time
proxies = [
"95.87.220.19:15600",
"91.67.240.45:3128",
"85.175.216.32:53281",
"91.236.251.131:8118",
"91.236.251.131:8118",
"88.99.10.249:1080",
]
def sol(ip):
max_tries = 5
for i in range(1, max_tries+1):
try:
print(f"Using Proxy: {ip}")
r = requests.get('https://api.myip.com', proxies={"https": ip})
print(f"Got Back: {r.json()}")
break
except OSError:
time.sleep(5)
print(f"Retrying...: {i}")
break
for i in proxies:
sol(i)
How can I make it s my loop has 5 tries before moving onto the next ip address.
My program does however work when the proxy is up for the first try as it breaks after the first attempt and then moves onto the next ip address.
It does this unconditionally, because you have an unconditional break after the except block. Code keeps going past a try/except when the except is entered, assuming it doesn't have an abnormal exit of its own (another exception, return etc.).
So,
I thought this except block would work but it is not breaking out of the loop when the 5 iterations are over and I am not sure why.
It doesn't break out "after the 5 iterations are over" because it breaks out after the first iteration, whether or not that attempt was successful.
If I understand correctly, you can just remove break from the last line. If you have an unconditional break in a loop, it will always iterate once.
def sol(ip):
max_tries = 5
for i in range(1, max_tries+1):
try:
print(f"Using Proxy: {ip}")
r = requests.get('https://api.myip.com', proxies={"https": ip})
print(f"Got Back: {r.json()}")
break
except OSError:
time.sleep(5)
print(f"Retrying...: {i}")
# break <---- Remove this line
Using retrying would look something like the following:
from retrying import retry
import requests
#retry(stop_max_attempt_number=5)
def bad_host():
print('trying get from bad host')
return requests.get('https://bad.host.asdqwerqweo79ooo/')
try:
bad_host()
except IOError as ex:
print(f"Couldn't connect because: {str(ex)}")
...which give the following output:
trying get from bad host
trying get from bad host
trying get from bad host
trying get from bad host
trying get from bad host
Couldn't connect to bad host because: HTTPSConnectionPool(host='bad.host.asdqwerqweo79ooo', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x10b6bd910>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))
Getting fancy
If you want to get fancy, you could also add things like exponential backoff and selectively retrying certain exceptions.
Here's an example:
import random
import time
def retry_ioerror(exception):
return isinstance(exception, IOError)
#retry(
wait_exponential_multiplier=100,
wait_exponential_max=1000,
retry_on_exception=retry_ioerror,
stop_max_attempt_number=10)
def do_something():
t = time.time()
print(f'trying {t}')
r = random.random()
if r > 0.9:
return 'yay!'
if r > 0.8:
raise RuntimeError('Boom!')
else:
raise IOError('Bang!')
try:
result = do_something()
print(f'Success! {result}')
except RuntimeError as ex:
print(f"Failed: {str(ex)}")
I understand the basic try: except: finally: syntax for pythons error handling. What I don't understand is how to find the proper error names to make readable code.
For example:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.settimeout(60)
char = s.recv(1)
except socket.timeout:
pass
so if socket raises a timeout, the error is caught. How about if I am looking for a connection refused. I know the error number is 10061. Where in the documentation do I look to find a meaning full name such as timeout. Would there be a similar place to look for other python modules? I know this is a newbie question but I have been putting in error handling my my code for some time now, without actually knowing where to look for error descriptions and names.
EDIT:
Thanks for all your responses.
would
except socket.error, exception:
if exception.errno == ETIMEDOUT:
pass
achieve the same result as
except socket.timeout:
pass
To achieve what you want, you'll have to grab the raised exception, extract the error code stored into, and make some if comparisons against errno codes:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.settimeout(60)
char = s.recv(1)
except socket.error, exception:
if exception.errno == errno.ECONNREFUSED:
# this is a connection refused
# or in a more pythonic way to handle many errors:
{
errno.ECONNREFUSED : manage_connection_refused,
errno.EHOSTDOWN : manage_host_down,
#all the errors you want to catch
}.get(exception.errno, default_behaviour)()
except socket.timeout:
pass
with :
def manage_connection_refused():
print "Connection refused"
def manage_host_down():
print "Host down"
def default_behaviour():
print "error"
You will get an error with an errno, which is described in the errno documentation. 10061 is only valid for WinSock.
According to socket, socket.error values are defined in the errno module.
Hey I'm wondering how to handle specific error codes. For example, [Errno 111] Connection refused
I want to catch this specific error in the socket module and print something.
If you want to get the error code, this seems to do the trick;
import errno
try:
socket_connection()
except socket.error as error:
if error.errno == errno.ECONNREFUSED:
print(os.strerror(error.errno))
else:
raise
You can look up errno error codes.
On Unix platforms, at least, you can do the following.
import socket, errno
try:
# Do something...
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
# Handle the exception...
else:
raise
Before Python 2.6, use e.args[ 0 ] instead of e.errno.
This seems hard to do reliably/portably but perhaps something like:
import socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 4167))
except socket.error, e:
if 'Connection refused' in e:
print '*** Connection refused ***'
which yields:
$ python socketexception.py
*** Connection refused ***
Pretty yucky though.
I'm developing on Windows and found myself in the same predicament. But the error message always contains the error number. Using that information I just convert the exception to a string str(Exception), convert the error code I wanna check for to a string str(socket.errno.ERRORX) and check if the error code is in the exception.
Example for a connection reset exception:
except Exception as errorMessage:
if str(socket.errno.ECONNRESET) in str(errorMessage):
print("Connection reset")
#etc...
This avoids locale specific solutions but is still not platform independent unfortunately.
Trying to get a handle on the FTP library in Python. :)
Got this so far.
from ftplib import FTP
server = '127.0.0.1'
port = '57422'
print 'FTP Client (' + server + ') port: ' + port
try:
ftp = FTP()
ftp.connect(server, port, 3)
print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"'
ftp.cwd('\\')
x = '1'
currentDir = ''
except: //***What do I put here?***
http://docs.python.org/library/ftplib.html
says there are several error codes I can catch but I can't do
except: ftplib.all_errors
Second question. :P
How can I retrieve more specific information on the error? Perhaps the error code?
Very new to python (an hour in or so).
I can't do
except: ftplib.all_errors
Of course not, that's simply bad syntax! But of course you can do it with proper syntax:
except ftplib.all_errors:
i.e., the colon after the tuple of exceptions.
How can I retrieve more specific
information on the error? Perhaps the
error code?
except ftplib.all_errors as e:
errorcode_string = str(e).split(None, 1)[0]
E.g., '530' will now be the value of errorcode_string when the complete error message was '530 Login authentication failed'.
You can find the rest of the exception in the docs.
You write
except Exception, e: #you can specify type of Exception also
print str(e)
You dont want to try catch an Exception class unless you have to. Exception is a catch all, instead catch the specific class being thrown, socket.error
import ftplib
import socket <--
server = '127.0.0.1'
port = '57422'
print 'FTP Client (' + server + ') port: ' + port
ftp = ftplib.FTP()
try:
ftp.connect(server, port, 3)
print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"'
ftp.cwd('\\')
x = '1'
currentDir = ''
except socket.error,e: <--
print 'unable to connect!,%s'%e