GSocket.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <LibGUI/GSocket.h>
  2. #include <LibCore/CNotifier.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <arpa/inet.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <netdb.h>
  9. #include <errno.h>
  10. GSocket::GSocket(Type type, CObject* parent)
  11. : GIODevice(parent)
  12. , m_type(type)
  13. {
  14. }
  15. GSocket::~GSocket()
  16. {
  17. }
  18. bool GSocket::connect(const String& hostname, int port)
  19. {
  20. auto* hostent = gethostbyname(hostname.characters());
  21. if (!hostent) {
  22. dbgprintf("GSocket::connect: Unable to resolve '%s'\n", hostname.characters());
  23. return false;
  24. }
  25. IPv4Address host_address((const byte*)hostent->h_addr_list[0]);
  26. dbgprintf("GSocket::connect: Resolved '%s' to %s\n", hostname.characters(), host_address.to_string().characters());
  27. return connect(host_address, port);
  28. }
  29. bool GSocket::connect(const GSocketAddress& address, int port)
  30. {
  31. ASSERT(!is_connected());
  32. ASSERT(address.type() == GSocketAddress::Type::IPv4);
  33. ASSERT(port > 0 && port <= 65535);
  34. struct sockaddr_in addr;
  35. memset(&addr, 0, sizeof(addr));
  36. auto ipv4_address = address.ipv4_address();
  37. memcpy(&addr.sin_addr.s_addr, &ipv4_address, sizeof(IPv4Address));
  38. addr.sin_family = AF_INET;
  39. addr.sin_port = htons(port);
  40. m_destination_address = address;
  41. m_destination_port = port;
  42. printf("Connecting to %s...", address.to_string().characters());
  43. fflush(stdout);
  44. int rc = ::connect(fd(), (struct sockaddr*)&addr, sizeof(addr));
  45. if (rc < 0) {
  46. if (errno == EINPROGRESS) {
  47. printf("in progress.\n");
  48. m_notifier = make<CNotifier>(fd(), CNotifier::Event::Write);
  49. m_notifier->on_ready_to_write = [this] {
  50. printf("%s{%p} connected!\n", class_name(), this);
  51. m_connected = true;
  52. m_notifier->set_event_mask(CNotifier::Event::None);
  53. if (on_connected)
  54. on_connected();
  55. };
  56. return true;
  57. }
  58. perror("connect");
  59. exit(1);
  60. }
  61. printf("ok!\n");
  62. m_connected = true;
  63. return true;
  64. }
  65. ByteBuffer GSocket::receive(int max_size)
  66. {
  67. auto buffer = read(max_size);
  68. if (eof()) {
  69. dbgprintf("GSocket{%p}: Connection appears to have closed in receive().\n", this);
  70. m_connected = false;
  71. }
  72. return buffer;
  73. }
  74. bool GSocket::send(const ByteBuffer& data)
  75. {
  76. int nsent = ::send(fd(), data.pointer(), data.size(), 0);
  77. if (nsent < 0) {
  78. set_error(nsent);
  79. return false;
  80. }
  81. ASSERT(nsent == data.size());
  82. return true;
  83. }