0

I was attempting to test for connection failure, and unfortunately it's not failing if the IP address of the host is fire walled.

This is the code:

def get_connection(self, conn_data):
    rtu, hst, prt, usr, pwd, db = conn_data  
    try:
        self.conn = pgdb.connect(host=hst+":"+prt, user=usr, password=pwd, database=db)
        self.cur = self.conn.cursor()
        return True
    except pgdb.Error as e:
        logger.exception("Error trying to connect to the server.")
        return False

if self.get_connection(conn_data):
    # Do stuff here:

If I try to connect to a known server but give an incorrect user name, it will trigger the exception and fail.

However if I try to connect to a machine that does not respond (firewalled) it never gets passed self.conn = pgdb.connect()

How to I wait or test for time out rather than have my app appear to hang when a user mistypes an IP address?

Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
Rob
  • 2,511
  • 2
  • 20
  • 31
  • Spelling/grammar-nazi time: Pythobn -> Python, fire walled -> firewalled. Oh, and the last line is not indented by four spacees, it seems. – Jürgen A. Erhard Mar 01 '10 at 11:36

2 Answers2

0

What you are experiencing is the pain of firewalls, and the timeout is the normal TCP timeout.

Teddy
  • 6,013
  • 3
  • 26
  • 38
  • s/of firewalls/of stupid, "paranoid" firewalls/ It's actually the result of a DROP rule. The proper way is to actually reply with a tcp-reset ICMP packet (IIRC). – Jürgen A. Erhard Mar 01 '10 at 11:35
0

You can usually pass timeout argument in connect function. If it doesn't exist you could try with socket.timeout or default timeout:

import socket
socket.setdefaulttimeout(10) # sets timeout to 10 seconds

This will apply this setting to all connections(socket based) you make and will fail after 10 seconds of waiting.

Seb
  • 17,141
  • 7
  • 38
  • 27