static int connect_device(char* host, char* buffer, int buffer_size) { int port, fd; char* portstr = strchr(host, ':'); char hostbuf[100]; char serial[100]; int ret; strncpy(hostbuf, host, sizeof(hostbuf) - 1); if (portstr) { if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) { snprintf(buffer, buffer_size, "bad host name %s", host); return 0; } // zero terminate the host at the point we found the colon hostbuf[portstr - host] = 0; if (sscanf(portstr + 1, "%d", &port) == 0) { snprintf(buffer, buffer_size, "bad port number %s", portstr); return 0; } } else { port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; } snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port); fd = socket_network_client_timeout(hostbuf, port, SOCK_STREAM, 10); if (fd < 0) { snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port); return 0; } D("client: connected on remote on fd %d\n", fd); close_on_exec(fd); disable_tcp_nagle(fd); enable_keepalive(fd); ret = register_socket_transport(fd, serial, port, 0); if (ret < 0) { adb_close(fd); snprintf(buffer, buffer_size, "already connected to %s", serial); return 0; } else { snprintf(buffer, buffer_size, "connected to %s", serial); } return 1; }
static void connect_device(const std::string& host, std::string* response) { if (host.empty()) { *response = "empty host name"; return; } std::vector<std::string> pieces = android::base::Split(host, ":"); const std::string& hostname = pieces[0]; int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; if (pieces.size() > 1) { if (sscanf(pieces[1].c_str(), "%d", &port) != 1) { *response = android::base::StringPrintf("bad port number %s", pieces[1].c_str()); return; } } // This may look like we're putting 'host' back together, // but we're actually inserting the default port if necessary. std::string serial = android::base::StringPrintf("%s:%d", hostname.c_str(), port); int fd = socket_network_client_timeout(hostname.c_str(), port, SOCK_STREAM, 10); if (fd < 0) { *response = android::base::StringPrintf("unable to connect to %s:%d", hostname.c_str(), port); return; } D("client: connected on remote on fd %d\n", fd); close_on_exec(fd); disable_tcp_nagle(fd); int ret = register_socket_transport(fd, serial.c_str(), port, 0); if (ret < 0) { adb_close(fd); *response = android::base::StringPrintf("already connected to %s", serial.c_str()); } else { *response = android::base::StringPrintf("connected to %s", serial.c_str()); } }
/* Connect to port on the IP interface. type is * SOCK_STREAM or SOCK_DGRAM. * return is a file descriptor or -1 on error */ int socket_network_client(const char *host, int port, int type) { return socket_network_client_timeout(host, port, type, 0); }