@helginet Maybe I'm wrong but...

I don't understand why we are looking for socket after connection fails.
Thought you should simply look for socket only if hostname="localhost"

Also what's going to happen if user provides ip for hostname, but wrong ip? For me it looks like we will try connect to socket.

... but as I said, maybe I'm wrong