This is a question about Berkeley sockets.
Normally, a client would connect to a server by calling the connect()
function, and a connection would be established assuming the target machine was reachable and an application on the target machine had already entered the listening state by calling the listen()
function. This also assumes that the client is attempting to connect to the correct port, and that the server is listening on that port number.
My question is what happens if connect()
fails for an external reason? Internal reasons would be things such as not having enough resources available, for example if a port is already in use, or system has run out of memory, etc.
The two important external reasons why connect()
may fail which I have in mind are:
- The target machine IP address is not reachable (no route to host, or no route to network, etc)
- The target machine does not have an open, listening port on the expected port number. (Most likely the listening server application is not running)
The reason this question arises is in the case of internal reasons for failure, these things are likely known by the time any functions or system calls return.
- For example, if an application attempts to
connect()
to a host and the required system resources are not available, then a call toconnect()
will likely return an error code at the time the function returns. This is likely the case becauseconnect()
probably produces some interaction with the OS via OS system calls, and these system calls will return error codes indicating the problem.
On the other hand, once a message/data packet is sent out of a network interface, the information about whether or not this was successful will not be known for some time.
- In the case of network not reachable, the OS might know in advance that it cannot route IP traffic to a certain subnet because there is no known route to that subnet. But it might not. "duckduckgo.com" might have been reachable 5 minutes ago, and now it might not be for some reason.
- Even if the OS does know that a packet is routable to a host in advance of sending it out of a network interface, it does not know what will happen to that packet on the way. (Filtered by firewall? Host machine may not have a certain port open and listening?)
In this case, what happens? I assume the connect()
function must return, but might return without an error even though an error is about to occur. (For an external reason, as described above.)
The reason for this question is I am trying to figure out the best way to deal with problems with an application I am developing, where the user enters an IP address of a server which either does not exist or does not respond. At the moment I don't know enough about how connect()
works in case of failure to know how to deal with this.
I should add that I also don't know if this is defined in some specification or whether this is undefined behaviour or OS dependent, for example.