+
+ /* If we've got a "connection refused" error, just return
+ -1. The caller will know what to do. */
+ if (
+#ifdef USE_WIN32API
+ err == WSAECONNREFUSED
+#else
+ err == ECONNREFUSED
+#endif
+ )
+ {
+ close (sock);
+ errno = err;
+ return -1;
+ }
+
+ if (
+ /* Any other error (except EINPROGRESS) will be "swallowed"
+ here. We return without specifying a return value, and
+ set errno if the caller wants to inspect what
+ happened. */
+#ifdef USE_WIN32API
+ /* Under Windows, calling "connect" with a non-blocking socket
+ results in WSAEWOULDBLOCK, not WSAEINPROGRESS. */
+ err != WSAEWOULDBLOCK
+#else
+ err != EINPROGRESS
+#endif
+ )
+ {
+ close (sock);
+ errno = err;
+ return -1;
+ }
+
+ /* Looks like we need to wait for the connect. */
+ int n;
+
+ do
+ n = wait_for_connect (sock, polls);
+ while (n == 0);
+
+ if (n < 0)
+ {
+ int saved_errno = errno;
+
+ /* A negative value here means that we either timed out or
+ got interrupted by the user. Just return. */
+ close (sock);
+ errno = saved_errno;
+ return -1;
+ }
+ }
+
+ /* Got something. Is it an error? */
+ int err;
+ socklen_t len = sizeof (err);
+
+ /* On Windows, the fourth parameter to getsockopt is a "char *";
+ on UNIX systems it is generally "void *". The cast to "char *"
+ is OK everywhere, since in C++ any data pointer type can be
+ implicitly converted to "void *". */
+ int ret = getsockopt (sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
+
+ if (ret < 0)
+ {
+ int saved_errno = errno;
+
+ close (sock);
+ errno = saved_errno;
+ return -1;
+ }
+ else if (ret == 0 && err != 0)
+ {
+ close (sock);
+ errno = err;
+ return -1;
+ }
+
+ /* The connection succeeded. Return the socket. */
+ return sock;
+}
+
+/* Open a tcp socket. */
+
+int
+net_open (struct serial *scb, const char *name)
+{
+ struct addrinfo hint;
+ struct addrinfo *ainfo;
+
+ memset (&hint, 0, sizeof (hint));
+ /* Assume no prefix will be passed, therefore we should use
+ AF_UNSPEC. */
+ hint.ai_family = AF_UNSPEC;
+ hint.ai_socktype = SOCK_STREAM;
+ hint.ai_protocol = IPPROTO_TCP;
+
+ parsed_connection_spec parsed = parse_connection_spec (name, &hint);
+
+ if (parsed.port_str.empty ())
+ error (_("Missing port on hostname '%s'"), name);
+
+ int r = getaddrinfo (parsed.host_str.c_str (),
+ parsed.port_str.c_str (),
+ &hint, &ainfo);
+
+ if (r != 0)
+ {
+ fprintf_unfiltered (gdb_stderr, _("%s: cannot resolve name: %s\n"),
+ name, gai_strerror (r));
+ errno = ENOENT;