When using java.net.Socket.connect(), both a refused connection and a timeout result in a ConnectException.
java.net.ConnectException: Connection timed out: connect
java.net.ConnectException: Connection refused: connect
How can I safely distinguish between the two? Sure parsing the error message does the job. But when the message changes in a future Java release, I’m out of luck.
The bigger picture: I’m writing a web service client using JAX-WS with a Metro implementation. When a web service call fails, I want to report the reason for the failure clearly so the issue can be resolved quickly.
Unfortunately, in the Sun JDK, this information isn’t made available anywhere but the string. See line 473 of PlainSocketImpl.c (for *ix), and net_util_md.c (for Windows). The *ix implementation does sometimes call NET_ThrowByNameWithLastError (from *ix net_util_md.c), which will include errno in the string; this function exists on Windows, but it’s not used here..
Thus, you have to rely on the strings and hope they don’t change. Sun does not seem to localize them, which makes sense because they’re not supposed to be user-facing. You can try to parse the errno out for a more stable error code.
You should also be sure to have a fall-back in case no string or errno matches.