erling
erling

Reputation: 451

Python socket connection exception

I have a socket-connection going on and I wanna improve the exception handling and I'm stuck. Whenever I call socket.connect(server_address) with an invalid argument the program stops, but doesn't seem to raise an exception. Here is my code:

import socket
import sys
import struct
class ARToolkit():
    
    def __init__(self):
        self.x = 0
        self.y = 0
        self.z = 0
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.logging = False
    
    def connect(self,server_address):
        try:
            self.sock.connect(server_address)
        except socket.error, msg:
            print "Couldnt connect with the socket-server: %s\n terminating program" % msg
            sys.exit(1)
    
    def initiate(self):
        self.sock.send("start_logging")
    
    def log(self):
        self.logging  = True  
        buf = self.sock.recv(6000)
        if len(buf)>0:
            nbuf = buf[len(buf)-12:len(buf)]
            self.x, self.y, self.z = struct.unpack("<iii", nbuf) 
    
    def stop_logging(self):
        print "Stopping logging"
        self.logging = False
        self.sock.close()
            

The class maybe looks a bit wierd but its used for receiving coordinates from another computer running ARToolKit. Anyway, the issue is at the function connect():

def connect(self,server_address):
    try:
        self.sock.connect(server_address)
    except socket.error, msg:
        print "Couldnt connect with the socket-server: %s\n terminating program" % msg
        sys.exit(1)

If I call that function with a random IP-address and portnumber the whole program just stops up at the line:

self.sock.connect(server_address)

The documentation I've read states that in case of an error it will throw a socket.error-exception. I've also tried with just:

except Exception, msg:

This, if I'm not mistaken, will catch any exceptions, and still it yields no result. I would be very grateful for a helping hand. Also, is it okay to exit programs using sys.exit when an unwanted exception occurs?

Thank you

Upvotes: 22

Views: 150986

Answers (2)

mhawke
mhawke

Reputation: 87054

If you have chosen a random, but valid, IP address and port, socket.connect() will attempt to make a connection to that endpoint. By default, if no explicit timeout is set for the socket, it will block while doing so and eventually timeout, raising exception socket.error: [Errno 110] Connection timed out.

The default timeout on my machine is 120 seconds. Perhaps you are not waiting long enough for socket.connect() to return (or timeout)?

You can try reducing the timeout like this:

import socket

s = socket.socket()
s.settimeout(5)   # 5 seconds
try:
    s.connect(('123.123.123.123', 12345))         # "random" IP address and port
except socket.error, exc:
    print "Caught exception socket.error : %s" % exc

Note that if a timeout is explicitly set for the socket, the exception will be socket.timeout which is derived from socket.error and will therefore be caught by the above except clause.

Upvotes: 25

user3960432
user3960432

Reputation:

The problem with your last general exception is the colon placement. It needs to be after the entire exception, not after the except statement. Thus to capture all exceptions you would need to do:

except Exception,msg:

However from Python 2.6+ you should use the as statement instead of a comma like so:

except Exception as msg:

I was able to run the code fine (note you need to throw in a tuple to the connect method). If you want to specifically catch only socket errors then you would need to except the socket.error class. Like you have:

except socket.error as msg:

If you want to make sure that a tuple is entered simply add another exception loop:

except socket.error as msg:
    print "Socket Error: %s" % msg
except TypeError as msg:
    print "Type Error: %s" % msg

Upvotes: 9

Related Questions