OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "remoting/client/plugin/host_connection.h" |
| 6 |
| 7 #include <netinet/in.h> |
| 8 #include <netdb.h> |
| 9 #include <sys/socket.h> |
| 10 |
| 11 #include <iostream> // TODO(garykac): Replace or remove debug output. |
| 12 |
| 13 #include "remoting/client/plugin/chromoting_plugin.h" |
| 14 |
| 15 namespace remoting { |
| 16 |
| 17 HostConnection::HostConnection() { |
| 18 connected_ = false; |
| 19 } |
| 20 |
| 21 HostConnection::~HostConnection() { |
| 22 } |
| 23 |
| 24 bool HostConnection::connect(const char* ip_address) { |
| 25 std::cout << "Attempting to connect to " << ip_address << std::endl; |
| 26 |
| 27 sock_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); |
| 28 if (sock_ < 0) { |
| 29 std::cout << "Can't open socket" << std::endl; |
| 30 return false; |
| 31 } |
| 32 |
| 33 hostent* server = gethostbyname(ip_address); |
| 34 if (!server) { |
| 35 std::cout << "Can't resolve address" << std::endl; |
| 36 return false; |
| 37 } |
| 38 |
| 39 sockaddr_in server_address; |
| 40 memset(&server_address, 0, sizeof(server_address)); |
| 41 server_address.sin_family = AF_INET; |
| 42 memcpy(&server_address.sin_addr.s_addr, server->h_addr, server->h_length); |
| 43 server_address.sin_port = htons(4000); |
| 44 |
| 45 if (::connect(sock_, reinterpret_cast<sockaddr*>(&server_address), |
| 46 sizeof(server_address)) < 0) { |
| 47 std::cout << "Cannot connect to server" << std::endl; |
| 48 return false; |
| 49 } |
| 50 |
| 51 connected_ = true; |
| 52 return true; |
| 53 } |
| 54 |
| 55 // Read data from a socket to a buffer. |
| 56 bool HostConnection::read_data(char* buffer, int num_bytes) { |
| 57 if (!connected_) { |
| 58 return false; |
| 59 } |
| 60 |
| 61 while (num_bytes > 0) { |
| 62 int num_bytes_read = read(sock_, buffer, num_bytes); |
| 63 if (num_bytes_read <= 0) { |
| 64 return false; |
| 65 } |
| 66 buffer += num_bytes_read; |
| 67 num_bytes -= num_bytes_read; |
| 68 } |
| 69 return true; |
| 70 } |
| 71 |
| 72 // Write data from a buffer to a socket. |
| 73 bool HostConnection::write_data(const char* buffer, int num_bytes) { |
| 74 if (!connected_) { |
| 75 return false; |
| 76 } |
| 77 |
| 78 while (num_bytes > 0) { |
| 79 int num_bytes_written = write(sock_, buffer, num_bytes); |
| 80 if (num_bytes_written <= 0) { |
| 81 return false; |
| 82 } |
| 83 num_bytes -= num_bytes_written; |
| 84 buffer += num_bytes_written; |
| 85 } |
| 86 return true; |
| 87 } |
| 88 |
| 89 } // namespace remoting |
OLD | NEW |