I haven't tested that yet, but if the connection will not be executed, will this last sentence be printed?
def connect_to():
print(f"[*] Connecting to {receiver_ip}:{receiver_port}")
socket.connect((receiver_ip, receiver_port))
print(f"[+] Connected")
How can I check if I connected properly and make a proper if statement?
When a socket fails to connect, it will raise a socket.error exception. You can catch that specific error using some error handling techniques in Python.
import socket
def connect(ip, port):
s = socket.socket()
try:
print(f"Connecting to {ip}:{port}")
s.connect((ip, port))
except socket.error as msg:
print(f"Failed to connect: {msg}")
else:
print(f"Successfully connected to {ip}:{port}")
How can I check if I connected properly and make a proper if statement?
The except block will be executed if the specified error is caught in the try block. On the other hand, the else block will be executed when no errors were raised or handled. You can view the except block as "if error" and the else block as "if not error".
Alternatively, you can catch an error and re-raise it with your custom message.
import socket
def connect(ip, port):
s = socket.socket()
try:
print(f"Connecting to {ip}:{port}")
s.connect((ip, port))
except socket.error as msg:
raise socket.error(f"Failed to connect: {msg}")
print(f"Successfully connected to {ip}:{port}")
By catching and re-raising, you don't have to use the else block anymore.
Use try except to catch the errors and if the connection is successful
I'm trying to connect through Paramiko to an external SFTP and passing an encrypted config file for the credentials. When attempting to connect with the following, I get an error for the exception client.close that states AttributeError: 'Nonetype' object has not attribute 'close':
client = None
try:
client = paramiko.Transport(hostname, port)
client.connect(username=username, password=password)
except Exception as e:
client.close()
return 'Cannot connect to SFTP server: ' + str(e.args[-1]), []
# Go
sftp = paramiko.SFTPClient.from_transport(client)
In the exception you're calling method client.close() which throws an error because the method client.connect did not succeeded, remove this method or create an exception for each possible error with to code handling that specific error.
I am new to Python and facing some issues with exception handling.
When I create a socket and connect it to an IP/port, I want to handle the socket exceptions and not display Python errors on console. I did that with the help of try and except.
try:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((self.host, self.port))
except error:
print 'Socket Error'
But I still get the error printed on console
error: uncaptured python exception, closing channel <SClient 20.0.0.1:5000 at 0x7fe94e0e2e18> (<class 'socket.error'>:[Errno 111] Connection refused [/usr/lib/python2.7/asyncore.py|read|83] [/usr/lib/python2.7/asyncore.py|handle_read_event|446] [/usr/lib/python2.7/asyncore.py|handle_connect_event|454])
Please advice
try:
a == b
except Exception as e:
print "error: %s"%(e)
Use this format.
I want to create socket errors (By doing things, obviously) but I've no idea how I should test if my script handles errors properly (If it dectes them.)
Currently, my code is this:
except socket.error as err:
print "Connection lost, waiting..."
time.sleep(5)
In theory, it should handle all the socket errors, print and then sleep (It's a part of a while loop.).
Any idea of how can I test it to see how it handles errors?
Use the raise statement:
try:
raise socket.error
except socket.error as err:
print "Connection lost, waiting..."
time.sleep(5)
Yet another example:
try:
raise AttributeError
except AttributeError:
print 'Sorry'
#Sorry
Also take a look at here and here
This question will expand on: Best way to open a socket in Python
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
Edit:
I tried this:
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
but the alert function is called even when that connection should have worked.
It seems that you catch not the exception you wanna catch out there :)
if the s is a socket.socket() object, then the right way to call .connect would be:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.
You can use the function connect_ex. It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as errno in C):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
print "problem with socket!"
else:
print "everything it's ok!"
You should really post:
The complete source code of your example
The actual result of it, not a summary
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it
doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
12 years later for anyone having similar problems.
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
doesn't work because the port '80' is a string. Your port needs to be int.
try:
s.connect((address, 80))
This should work.
Not sure why even the best answer didnt see this.