Put the socket-closing functionality in a 'finally' statment rather than in a 'except KeyboardInterrupt' to ensure that the socket it closed regardless of the type of exception that gets thrown.