What is the correct way to connect a non-blocking socket in Linux

I am new to socket programming on Linux and am wondering about the correct way to create a non-blocking connection.

I created a socket descriptor and set O_NONBLOCK for non-blocking I / O. I call connect, which returns EINPROGRESS, and then I call select, with a timeout value.

How do I know how long the connect () operation will take to wait? Can I change this in my program?

If my select operation time out, then what? Is it okay to close the socket descriptor, create another, and then reconnect? Or is there a way to cancel a connection in an existing socket and retry the operation using the same socket descriptor?

Thanks.

+5
source share
2 answers

When the connection is completed, the FD socket will be writable. You should also check for the latest socket error through getsockopt ().

How do I know how long the connect () operation will take to wait?

You cannot, of course. You must try. The question does not make sense.

Can I change this in my program?

You can change the timeout of the selection if that is what you mean. If this is not the case, I do not understand the question. Note that you can reduce the default connection timeout by default in about a minute, but you cannot increase it.

If my select operation time out, then what?

You close the socket and fulfill all the requirements of your application for a connection timeout.

Is it okay to close the socket descriptor, create another one, and then reconnect?

Only if you have reason to think that next time you will get a different result.

Or is there a way to cancel a connection in an existing socket and retry the operation using the same socket descriptor?

Not. After the connection failed, the socket will be dead and should be closed.

+1
source

How do I know how long the connect () operation will take to wait?

Not. You must decide in advance what a reasonable timeout will be for your needs, and then pass this value to select() . I usually use somewhere between 5-30 seconds, depending on the type of network my applications are running on.

Can I change this in my program?

Ultimately, no. The OS controls the timeout for connecting to a timeout. There may be OS-specific settings that you can configure to adjust this timeout, but that would not be portable or recommended.

If my select operation time out, then what?

The only thing you can do is close the socket and try again.

Is it okay to close the socket descriptor, create another one, and then reconnect?

Yes.

Or is there a way to cancel a connection in an existing socket and retry the operation using the same socket descriptor?

Not.

+1
source

Source: https://habr.com/ru/post/1201094/


All Articles