To prevent the connect function from blocking forever, a timeout can be implemented with select.
The function below takes the same arguments as connect and in addition a timeout argument, which sets the maximum time to wait to connect. The function returns 0 if the connection could be established within the given time. It returns 1 if the connection timed out and -1 if an error occured. Additionally, errno is set to ETIMEDOUT if the connection timed out.